[英]SQL Server Cumulative Sum by Group
我有這種格式的表(SQL Server 2005):
dummy_id,date_registered,item_id,數量,價格
並且我想添加一個新列( cumulative ),該列按date_registered計算每個item_id訂單的累計總數,如下所示:
dummy_id date_registered item_id quantity price cumulative
1 2013-07-01 100 10 34.5 10
2 2013-07-01 145 8 2.3 8
3 2013-07-11 100 20 34.5 30
4 2013-07-23 100 15 34.5 45
5 2013-07-24 145 10 34.5 18
提前感謝
在SQL Server 2005中,我將使用相關子查詢來執行此操作:
select dummy_id, date_registered, item_id, quantity, price,
(select sum(quantity)
from t t2
where t2.item_id = t.item_id and
t2.date_registered <= t.date_registered
) as cumulative
from table t;
如果您確實要將其添加到表中,則需要更改表以添加列,然后進行更新。 如果表具有插入和更新,則將需要添加觸發器以使其保持最新狀態。 通過查詢獲取它絕對容易。
在SQL Server 2012中,可以使用以下語法執行此操作:
select dummy_id, date_registered, item_id, quantity, price,
sum(quantity) over (partition by item_id order by date_registered) as cumulative
from table t;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.