27,580
社区成员
发帖
与我相关
我的任务
分享
declare @t table(a int,b numeric(5,2),c numeric(5,2))
insert into @t select 1,1.2,1.2
insert into @t select 2,1.3,1.3
insert into @t select 3,1.4,1.4
insert into @t select 4,1.5,1.5
insert into @t select 5,1.6,1.6
select * from @t a
union all
select * from (
select a.a,sum(b.b) b,sum(b.c) c from @t a,@t b
where a.a>=b.a
group by a.a ) b
order by a.a,a.b
a b c
----------- --------------------------------------- ---------------------------------------
1 1.20 1.20
1 1.20 1.20
2 1.30 1.30
2 2.50 2.50
3 1.40 1.40
3 3.90 3.90
4 1.50 1.50
4 5.40 5.40
5 1.60 1.60
5 7.00 7.00
(10 行受影响)
如果子查询效率太低,可以换成:
declare @t table(a int,b numeric(5,2),c numeric(5,2))
insert into @t select 1,1.2,1.2
insert into @t select 2,1.3,1.3
insert into @t select 3,1.4,1.4
insert into @t select 4,1.5,1.5
insert into @t select 5,1.6,1.6
select * from
(select * from @t
union all
select t.a,sum(h.b),sum(h.c) from @t t,@t h where h.a<=t.a group by t.a)k
order by a,b
declare @t table(a int,b numeric(5,2),c numeric(5,2))
insert into @t select 1,1.2,1.2
insert into @t select 2,1.3,1.3
insert into @t select 3,1.4,1.4
insert into @t select 4,1.5,1.5
insert into @t select 5,1.6,1.6
select * from
(select * from @t
union all
select a,(select sum(b) from @t where a<=t.a),(select sum(c) from @t where a<=t.a) from @t t)k
order by a,b