如何在SQL中找到两列的运行总和

3

我有一个如下的表:

month region    value
4/1/20  eu-west-2   110
3/1/20  eu-west-2   30
2/1/20  eu-west-2   13
2/1/20  us-west-2   2
1/1/20  us-west-2   242
4/1/20  us-west-2   240

我希望能够针对每个地区每个月的“value”列进行累加求和。例如:使用上述示例,答案应为:

month region cumulative_sum
4/1/20 eu-west-2  153
3/1/20 eu-west-2  43
2/1/20 eu-west-2  13
4/1/20 us-west-2  484
2/1/20 us-west-2  244
1/1/20 us-west-2  242

当我只需要找到每个月的累积总和时,我可以成功地编写查询语句,但是如果我加上地区,它就不起作用了:

select
month, sum(value) over (order by month rows unbounded preceding) as cumulative_sum
from table

但是当我这样做时:

  select
    month, region, sum(value) over (order by month,region rows unbounded preceding) as cumulative_sum
    from table

它给出了错误的结果。

请帮忙。

2个回答

4
假设month是一个日期类型的列,您可以执行以下操作:
select
    month,
    region,
    sum(value) over(
        partition by region, date_trunc('month', month)
        order by month
    ) cumulative_sum
from mytable

窗口函数 sum() 中的 partition by 子句将属于同一月份和地区的行组合在一起。每当地区更改或新月份开始时,总和会重置。

2
您很接近了,只是缺少了partition by
select month, region,
       sum(value) over (partition by region order by month rows unbounded preceding) as cumulative_sum
from table

糟糕,我刚刚忘记了分区子句。非常感谢! - user10096621

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接