34,576
社区成员
发帖
与我相关
我的任务
分享
update #
set @x2=case when @x1 is null or @x1 <> x1 then x2 else @x2+x2 end,
@x1=x1,
x2=@x2
declare @table table (X1 int,X2 int)
insert into @table
select 2,453 union all
select 2,120 union all
select 2,101 union all
select 2,89 union all
select 3,111 union all
select 3,421 union all
select 3,219
;with maco as
(
select *,row_number() over (partition by X1 ORDER BY X1) AS RID from @table
)
select X1,(select sum(X2) from maco
where X1=t.X1 AND RID<=t.RID) AS X2 from maco t
/*
X1 X2
----------- -----------
2 453
2 573
2 674
2 763
3 111
3 532
3 751
*/
CREATE TABLE temptb(
`x1` INT NULL NULL ,
`x2` INT NULL NULL );
INSERT INTO temptb VALUES(2,453);
INSERT INTO temptb VALUES(2,120);
INSERT INTO temptb VALUES(2,101);
INSERT INTO temptb VALUES(2,89);
INSERT INTO temptb VALUES(3,111);
INSERT INTO temptb VALUES(3,421);
INSERT INTO temptb VALUES(3,219);
create table #t (X1 int, X2 int)
insert #t
select 2, 453 union all
select 2, 120 union all
select 2, 101 union all
select 2, 89 union all
select 3, 111 union all
select 3, 421 union all
select 3, 219
with cte as
(
select *,ID=row_number() over(partition by X1 order by X1) from #t
)
select X1,X2=(select sum(X2) from cte a where a.X1=b.X1 AND a.ID<=b.ID) FROM cte b
/*
X1 X2
----------- -----------
2 453
2 573
2 674
2 763
3 111
3 532
3 751
(7 row(s) affected)
select *,id=identity(1,1) into #1
from 原始表
select x1,x2,(select sum(x2) from # a where a.x1=#1.X1 and a.id>=#1.id)
from #1
drop table #1