SQL Server中的复合SUM

时间:2014-03-10 11:56:11

标签: sql sql-server

是否可以在sql server中获得复合总和? e.g。

月薪总额

Jan 1000 1000

2月 1200 2200

3月 1000 3200

。 。

。 。

请帮忙。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

如果表格结构类似于此table(id int identity(1,1),month varchar(10),salary int,total int)

然后你可以尝试:

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

DEMO