如何在SQL中用group运行和?

时间:2018-06-13 12:19:48

标签: sql group-by amazon-redshift

现在我有一个如下表格

    Date        Promotion campaign    Visit      Orders    Revenue
   2018-06-01    Promotion01           200         5       1000
   2018-06-01    Promotion02           250         10      1100
   2018-06-02    Promotion01           220         8       1350
   2018-06-03    Promotion03           300         15      2000  
    ...

我想生成一个表格,显示累计数字,如

    Date         Visit        Orders       Revenue  
  2018-06-01      450           15           2100
  2018-06-02      670           23           3450
  2018-06-03      970           38           5450 

我首先知道我可能必须按功能使用分组并按日期对数据进行分组,然后如何为3列分配运行总和?

dw是亚马逊 - 红移。非常感谢您的帮助!

1 个答案:

答案 0 :(得分:4)

您可以使用聚合和窗口函数:

select date, sum(visit) as visit, sum(orders) as orders,
       sum(revenue) as revenue,
       sum(sum(revenue)) over (order by date) as running_revenue
from t
group by date
order by date;