比如表t1的数据如下:
id amount
1 30
2 40
3 50
4 60我想把t1的表的数据变成这样:
id amount
1 30
2 70
3 120
4 180从id=1开始,amount=30不变,当id=2时,上一个amount+当前的amount=30+40=70;当id=3时,
上一个amount+当前的amount=70+50=120,以此类推。
假如t1的表如下:
id amount
1 0
2 10
3 20
4 30把t1的表数据变成如下:
id amount
1 0
2 10
3 30
4 60从id=1开始,amount=0不变,当id=2时,上一个amount+当前的amount=0+10=10;当id=3时,
上一个amount+当前的amount=10+20=30,以此类推。
请问这个sql语句如何写?
id amount
1 30
2 40
3 50
4 60我想把t1的表的数据变成这样:
id amount
1 30
2 70
3 120
4 180从id=1开始,amount=30不变,当id=2时,上一个amount+当前的amount=30+40=70;当id=3时,
上一个amount+当前的amount=70+50=120,以此类推。
假如t1的表如下:
id amount
1 0
2 10
3 20
4 30把t1的表数据变成如下:
id amount
1 0
2 10
3 30
4 60从id=1开始,amount=0不变,当id=2时,上一个amount+当前的amount=0+10=10;当id=3时,
上一个amount+当前的amount=10+20=30,以此类推。
请问这个sql语句如何写?
select id,(select sum(amount) from tb where id <= t.id) as amount
from tb t
declare @table table (id int,amount int)
insert into @table
select 1,30 union all
select 2,40 union all
select 3,50 union all
select 4,60select id,amount=
(select sum(amount) from @table where id<=t.id) from @table t
/*
id amount
----------- -----------
1 30
2 70
3 120
4 180
*/
insert into tb select 1,30
insert into tb select 2,40
insert into tb select 3,50
insert into tb select 4,60
go
;with cte as(
select top 1 * from tb order by id
union all
select a.id,a.amount+b.amount from tb a inner join cte b on a.id=b.id+1
)select * from cte
go
drop table tb
/*id amount
----------- -----------
1 30
2 70
3 120
4 180(4 行受影响)*/