日期:2014-05-17  浏览次数:20547 次

这种要求要怎么写sql,求总和。
比如说我的表是这样子
ID    Name    Num1    Time
1      a        3     2013-10-10
2      b        2     2013-10-10
3      c        6     2013-10-10
4      d        1     2013-10-10

想得到的结果是这样子
ID    Name    Num1    Time          Count
1      a        3     2013-10-10     3
2      b        2     2013-10-10     5    
3      c        6     2013-10-10     11
4      d        1     2013-10-10     12

Count的意思是当前行Num1和前面所有Num1的总和
这样要怎么写。

------解决方案--------------------

;with cte(ID,Name,Num1,[Time]) as
(
select 1,'a',3,'2013-10-10'
union all select 2,'b',2,'2013-10-10'
union all select 3,'c',6,'2013-10-10'
union all select 4,'d',1,'2013-10-10'
)
select *,count=(select sum(Num1) from cte b where b.id<=a.id)
from cte a 

/*
ID Name Num1 Time count
1 a 3 2013-10-10 3
2 b 2 2013-10-10 5
3 c 6 2013-10-10 11
4 d 1 2013-10-10 12
*/