这种要求要怎么写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
/*
IDNameNum1Timecount
1a32013-10-103
2b22013-10-105
3c62013-10-1011
4d12013-10-1012
*/