sql server - Calculating cumulative sum in ms-sql -


i have table tblsumdemo following structure

billingid  qty  percent_of_qty  cumulative     1        10      5              5    2        5       8              13(5+8)    3        12      6              19(13+6)    4        1       10             29(19+10)    5        2       11             40(11+10)  

this have tried

declare @s int  select billingid, qty, percent_of_qty,        @s = @s + percent_of_qty cumulative tblsumdemo cross join (select @s = 0) var order billingid 

but i'm not able desired output,any appreciated , thanks

you can use cross apply:

select      t1.*,     x.cumulative tblsumdemo t1 cross apply(     select          cumulative = sum(t2.percent_of_qty)     tblsumdemo t2     t2.billingid <= t1.billingid )x 

for sql server 2012+, can use sum over():

select *,     cummulative = sum(percent_of_qty) over(order billingid) tblsumdemo 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -