How Get Cumulative Sum (with Sum of the Past) in SQL Server -


i work sql server 2008.

in db have table items has sample data:

id     |date      |title    |price ----------------------------------- 1      |20150310  |a        |100    2      |20150201  |b        |25    3      |20140812  |c        |225    4      |20130406  |d        |110    5      |20150607  |e        |645    6      |20120410  |f        |450    7      |20130501  |g        |325    8      |20150208  |h        |175    

i want have cumulative sum of price column after 20150101 (with sum of past).

in fact want results this:

date      |title        |price    |cum_sum   |before_cum_sum ---------------------------------------------------------------           |sum of past  |         |         |1110 20150201  |b            |25       |1135     | 20150208  |h            |175      |1310     | 20150310  |a            |100      |1410     | 20150607  |e            |645      |2055     | 

how result in sql server ?

op wants specific output - comply:

declare @items table ([date] datetime, title varchar (100), price money) insert @items values ('20150310','a',100), ('20150201','b',25 ), ('20140812','c',225), ('20130406','d',110),   ('20150607','e',645),   ('20120410','f',450),   ('20130501','g',325),   ('20150208','h',175) ;with p_cte (   select     *   , rowno = row_number() on (order date)       @items ), p2_cte (   select     p_cte.date   , p_cte.title   , p_cte.price   , p_cte.rowno   , cum_sum = price   , before_cum_sum = convert (money, 0)       p_cte   p_cte.rowno = 1   union   select     cur.date   , cur.title   , cur.price   , cur.rowno   , cum_sum = cur.price + prev.cum_sum   , before_cum_sum = prev.cum_sum       p_cte cur   inner join p2_cte prev on     prev.rowno = cur.rowno - 1 ) select top 1   date = convert (datetime, null) , title = 'sum of past' , price = convert (money, null) , rowno = convert (int, null) , cum_sum = convert (money, null) , p2_cte.before_cum_sum p2_cte date > '20150101' union select   * p2_cte date > '20150101' 

output looks this: enter image description here


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -