添加运行总计/累计列

时间:2017-03-07 22:30:57

标签: sql postgresql

我想在2015年的表格中获得每Actual_Sale_Date个销售额的累计总数,但到目前为止我的所有尝试都是徒劳的。我看了一下附加的链接并模仿了这个过程,但没有收获。有人可以帮忙吗?

Calculating Cumulative Sum in PostgreSQL

select Actual_Sale_Date, extract(week from Actual_Sale_Date) as week_number, 
count(*) from mytable
where extract(year from Actual_Sale_Date) = 2015

结果:(请求Running_Total)

 Actual_Sale_Date         week_number          count           running_total
2015-01-04 00:00:00           1                  1                 1
2015-01-06 00:00:00           2                  3                 4
2015-01-08 00:00:00           2                  4                 8
2015-01-09 00:00:00           2                  5                 13
2015-01-11 00:00:00           2                  1                 14
2015-01-15 00:00:00           3                  2                 16
2015-01-21 00:00:00           4                  1                 17
2015-01-23 00:00:00           4                  4                 21
2015-01-24 00:00:00           4                  1                 22
2015-01-26 00:00:00           5                  2                 24

1 个答案:

答案 0 :(得分:3)

只需使用窗口功能:

select Actual_Sale_Date, extract(week from Actual_Sale_Date) as week_number, 
       count(*),
       sum(count(*)) over (order by Actual_Sale_Date)
from ??
where extract(year from Actual_Sale_Date) = 2015
group by Actual_Sale_Date, extract(week from Actual_Sale_Date);