求助:在某一列上,求每一行之前该组的累计和
数据是这样的:
name,date,num
-----------------------
a,1-1号,1
b,1-2号,4
a,1-3号,8
a,1-4号,5
b,1-5号,6
b,1-6号,9
想统计出这样的结果
name,date,num,total
---------------------
a,1-1号,1,1
a,1-3号,8,9
a,1-4号,8,17(解释:a这一组当前行之前有两行,在该行统计时就是前两行num列值+本行num列值)
b,1-2号,4,4
b,1-5号,6,10
b,1-6号,9,19
请高手指教,立马给分!
[解决办法]
goif object_id('[tbl]') is not null drop table [tbl]gocreate table [tbl]([name] varchar(1),[date] varchar(5),[num] int)goinsert [tbl]select 'a','1-1号',1 union allselect 'b','1-2号',4 union allselect 'a','1-3号',8 union allselect 'a','1-4号',5 union allselect 'b','1-5号',6 union allselect 'b','1-6号',9;with tas(select ROW_NUMBER()over(partition by nameorder by getdate()) as id,*,num as total from tbl),m as(select id,name,[date],num,total from t where id=1union allselect a.id,a.name,a.[date],a.num,b.total+a.num from t ainner join m b on a.id=b.id+1 and a.name=b.name)select name,[date],num,total from m order by name/*name date num totala 1-3号 8 8a 1-4号 5 13a 1-1号 1 14b 1-2号 4 4b 1-5号 6 10b 1-6号 9 19*/刚刚看错了你是要按照name来分别统计的,修改了一下
[解决办法]
declare @tb table ([name] varchar(1),[date] varchar(5),[num] int) insert into @tb values('a','1-1号',1),('b','1-2号',4),('a','1-3号',8),( 'a','1-4号',8 ),('b','1-5号',6),('b','1-6号',9)select name,num,date,total from ( select *, ( select SUM([num]) from ((select *,rn=ROW_NUMBER()over(partition by name order by name,date ) from @tb) )m where s.name=m.name and s.date>=m.date) as totalfrom (select *,rn=ROW_NUMBER()over(partition by name order by name,date ) from @tb)s )e order by name,date name num date total---- ----------- ----- -----------a 1 1-1号 1a 8 1-3号 9a 8 1-4号 17b 4 1-2号 4b 6 1-5号 10b 9 1-6号 19(6 行受影响)
[解决办法]
declare @tb table ([name] varchar(1),[date] varchar(5),[num] int) insert into @tb values('a','1-1号',1),('b','1-2号',4),('a','1-3号',8),( 'a','1-4号',8 ),('b','1-5号',6),('b','1-6号',9)select name,num,date,total from ( select *, ( select SUM([num]) from ((select * from @tb) )m where s.name=m.name and s.date>=m.date) as totalfrom (select * from @tb)s )e order by name,date name num date total---- ----------- ----- -----------a 1 1-1号 1a 8 1-3号 9a 8 1-4号 17b 4 1-2号 4b 6 1-5号 10b 9 1-6号 19(6 行受影响)