我有下表:
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
加起来,直到Date
与ID
相关联,这意味着我希望得到这个:
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
如何传递所有相同ID
且Date
更小的记录。
答案 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.