SQL Server Cumulative Sum by Group -


i have table (sql server 2005) of format:

dummy_id, date_registered, item_id, quantity, price

and want add new column (cumulative) calculates cumulative totals of each item_id order date_registered shown:

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 

thanx in advance

in sql server 2005, using correlated subquery:

select dummy_id, date_registered, item_id, quantity, price,        (select sum(quantity)         t t2         t2.item_id = t.item_id ,               t2.date_registered <= t.date_registered        ) cumulative table t; 

if want add table, need alter table add column , update. if table has inserts , updates, need add trigger keep up-to-date. getting through query easier.

in sql server 2012, can using syntax:

select dummy_id, date_registered, item_id, quantity, price,        sum(quantity) on (partition item_id order date_registered) cumulative table t; 

Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

php - joomla get content in onBeforeCompileHead function -