2

Is it possible to get compounded sum in sql server? e.g.

Month Salary Total

Jan 1000 1000

Feb 1200 2200

Mar 1000 3200

. . .

. . .

Please help.

John
  • 704
  • 3
  • 12
  • 29

2 Answers2

3
Declare @t table( Months varchar(10), Salary int) 
insert into @t
select 'Jan', 1000 union all
select 'Feb', 1200 union all
select 'Mar', 1000
;With CTE as
(
select *,ROW_NUMBER()over(order by (select null))rn from @t
)
,CTE1 as
(
select a.*,salary [Total] from CTE a where rn=1
union all
select a.*,a.Salary+Total from CTE a inner join CTE1 b on a.rn-b.rn=1
)
select * from cte1
KumarHarsh
  • 5,046
  • 1
  • 18
  • 22
2

if the table structure's like this table(id int identity(1,1),month varchar(10),salary int,total int)

then you could try :

select *,(select sum(salary) 
          from table b  
          where b.id<=a.id) as total 
from table a

DEMO

Milen
  • 8,697
  • 7
  • 43
  • 57
vhadalgi
  • 7,027
  • 6
  • 38
  • 67