日期:2014-05-17 浏览次数:20663 次
create table #tb(时间 varchar(10),值 int)
insert into #tb
select '20120101',200
union all select '20121121',212
union all select '20120104',100
union all select '20120411',210
union all select '20120501',100
union all select '20120401',200
union all select '20120104',400
select *,累计值=(select sum(值) from (select *,rn=row_number() over(order by 时间) from #tb) b where b.rn<=a.rn)
from
(
select *,rn=row_number() over(order by 时间) from #tb
)a
order by 时间
/*
时间 值 累计值
-----------------------
20120101 200 200
20120104 100 300
20120104 400 700
20120401 200 900
20120411 210 1110
20120501 100 1210
20121121 212 1422
*/
WITH a AS
(
SELECT 20120101 AS tim,200 AS val UNION ALL
SELECT 20121121, 212 UNION ALL
SELECT 20120104 , 100 UNION ALL
SELECT 20120411 , 210 UNION ALL
SELECT 20120501 , 100 UNION ALL
SELECT 20120401 , 200 UNION ALL
SELECT 20120104 , 400
)
SELECT tim,val,(SELECT SUM(ISNULL(val,0)) FROM a WHERE tim<=b.tim) AS lj FROM a b
ORDER BY b.tim
/*
tim val &n