sql:汇总所有以前的分组行

时间:2017-08-30 09:07:51

标签: sql postgresql running-total

我有下表:

  date     | shop_id | package_id | quantity
01/01/2017 |   1     |    1       |    1
01/01/2017 |   1     |    2       |    5
01/01/2017 |   2     |    1       |    10
01/01/2017 |   2     |    2       |    4
02/01/2017 |   1     |    1       |    14
02/01/2017 |   1     |    2       |    3
  ....

我想将具有相同商店和相同包装的所有先前记录的数量相加,如下所示

  date     | shop_id | package_id | sum_quantity
01/01/2017 |   1     |    1       |    1
01/01/2017 |   1     |    2       |    5
01/01/2017 |   2     |    1       |    10
01/01/2017 |   2     |    2       |    4
02/01/2017 |   1     |    1       |    15
02/01/2017 |   1     |    2       |    8

  ....

1 个答案:

答案 0 :(得分:4)

这是基于shop_id和package_id的“运行总和”:

select "date", shop_id, package_id,
       sum(quantity) over (partition by shop_id, package_id order by "date") as sum_quantity
from the_table
order by "date";

sum()用作window function(通过over()部分)。窗口定义中的order by使其成为“运行”总和,而不是“总体”总和。

在线示例:http://rextester.com/ZOSK13092