【问题标题】:How to find running sum over two columns in SQL如何在SQL中找到两列的运行总和
【发布时间】:2020-08-15 10:29:34
【问题描述】:

我有一张这样的桌子:

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

我想找到每个区域每个月的“值”列的累积总和。例如:使用上面的示例答案应该是:

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

它给出了错误的结果。

请帮忙。

【问题讨论】:

    标签: sql select amazon-redshift window-functions cumulative-sum


    【解决方案1】:

    你已经很接近了,只是你错过了partition by

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

    【讨论】:

    • 糟糕,我刚刚忘记了分区子句。非常感谢!!
    【解决方案2】:

    假设month 是日期类数据类型的列,您可以这样做:

    select
        month,
        region,
        sum(value) over(
            partition by region, date_trunc('month', month)
            order by month
        ) cumulative_sum
    from mytable
    

    窗口sum()partition by 子句将属于同一月份和同一地区的行放在一起。每次地区变化或新月份开始时,总和都会重置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-14
      相关资源
      最近更新 更多