SQL SERVER TUTORIAL IN DEPTH

The blog is to help users about sql server

Others

LightBlog

Breaking

Friday, 20 December 2013

How To Calculate Cummulative Sum


create table cummulativetable
(

salary int

)

insert into cummulativetable values(100)
insert into cummulativetable values(200)
insert into cummulativetable values(300)
insert into cummulativetable values(400)
insert into cummulativetable values(500)

select * from cummulativetable













----------------------------USING CTE-------------------------------
;with cte(rownumber,salary)
as
(
select row_number() over( order by salary) as rownumber,salary
from cummulativetable
)
select rownumber,salary,
(
select sum(salary)
from 
cte c1
where c1.rownumber <= c2.rownumber

from cte c2



Trick 2 :


;with cte(rownumber,salary)
as
(
select row_number() over( order by salary) as rownumber,salary
from cummulativetable
),cte1(rownumber,salary,sumrows)
as
(
    select rownumber,salary,
    (
select sum(salary)
from
cte c1
where c1.rownumber <= c2.rownumber
)
    from cte c2
)

select * from cte1


Trick 3:
declare @salary int
declare @total int
set @total=0;
declare cur_cummulative cursor 
for
select salary from cummulativetable
for 
update of [cummulativesum]
open cur_cummulative 
fetch next from cur_cummulative into @salary

while @@fetch_status=0
begin
set @total+=@salary
update cummulativetable set cummulativesum=@total 
--where current of cur_cummulative
--where salary=@salary
--current of cur_cummulative

fetch next from cur_cummulative into @salary
end

select * from cummulativetable

close cur_cummulative
deallocate cur_cummulative


Both works...I have commented...you can use any one of it.
---.>update cummulativetable set cummulativesum=@total       where current of cur_cummulative
--->update cummulativetable set cummulativesum=@total  where salary=@salary





No comments:

Post a Comment

 test