如何用PostgreSQL进行条件求和?

时间:2015-06-29 10:44:11

标签: sql postgresql

我有下表:

ID  Quantity     date
100    20     1-NOV-15
100    30     1-OCT-15
100    10     1-OCT-15
100    5      1-AUG-15
101    4      1-AUG-15

我希望将ID的所有Quantity加起来,直到DateID相关联,这意味着我希望得到这个:

ID  Quantity     Date      sum
100    20     1-NOV-15      65       // sum all ID 100 till 1-NOV-15
100    30     1-OCT-15      45       // sum all ID 100 till 1-OCT-15
100    10     1-OCT-15      45       // sum all ID 100 till 1-OCT-15
100    5      1-AUG-15       5       // sum all ID 100 till 1-AUG-15
101    4      1-AUG-15       4       // sum all ID 101 till 1-AUG-15

我无法获得此结果。这就是我写的:

Select ID,Date,SUM(Quantity)
From a
Group by ID,Date
order by ID

我无法告诉SUM如何传递所有相同IDDate更小的记录。

1 个答案:

答案 0 :(得分:4)

You want a cumulative or running sum.

Select ID, Date, SUM(Quantity) OVER (PARTITION BY ID ORDER BY DATE)
From a;

EDIT:

The default framing option is range between unbounded preceding and current row as opposed to rows between unbounded preceding and current row. If you used the latter, the results would be more like:

ID  Quantity     Date      sum
100    20     1-NOV-15      65       // sum all ID 100 till 1-NOV-15
100    30     1-OCT-15      45       // sum all ID 100 till 1-OCT-15
100    10     1-OCT-15      15       // sum all ID 100 till 1-OCT-15
100    5      1-AUG-15       5       // sum all ID 100 till 1-AUG-15
101    4      1-AUG-15       4       // sum all ID 101 till 1-AUG-15

However, the default is appropriate for this problem.