Monday 7 July 2014

SQL Server Cummulative Sum

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;

Output:
  ID  Date     Item     Qty   Price      Cumm
1 14-05-2014 1201 5 100 100
2 18-05-2014 2012 1.05 300 400
3 25-05-2014 2013 5.8 50 450
4 31-05-2014 2014 20 400 850