如何把SQL表中的第一行数据更新到第二行中

2024-11-30 04:14:00
推荐回答(5个)
回答1:

Create Table #TMP
(
ID int identity(1,1),
firstBalance int,
lastBalance int


Insert Into #TMP (lastBalance) Values(1)
Insert Into #TMP (lastBalance) Values(3)
Insert Into #TMP (lastBalance) Values(5)
Insert Into #TMP (lastBalance) Values(2)
Insert Into #TMP (lastBalance) Values(9)
Insert Into #TMP (lastBalance) Values(10)
Select  (Select lastBalance From #Tmp C Where ID=(Select Max(ID) From #Tmp A Where A.ID<#TMP.ID)) As firstBalance ,lastBalance From #TMP 
Drop Table #TMP

--表需要一个自增的ID,如果没有,给个排序的字段也可!

回答2:

select a,b,c,lag(c) over(order by a) as AA from t_a;
这样,AA就是你要的值了,然后做一个更新语句。

回答3:

-- M$SQL:

update a set a=b.C, C=b.C-a.B
from T_A as a
JOIN T_A as b on a.Id + 1 = b.Id

回答4:

create table #temp1
(
[id] [int] IDENTITY(1,1) NOT NULL,
[a] [int] NULL,
[b] [int] NULL,
[c] [int] NULL
)

insert into #temp1 (a,b,c) values(10,3,7)
declare @i int
set @i = 1
while @i < 30
begin
insert into #temp1 (a,b,c)
select c,b,c-b from #temp1 where id = @i
set @i = @i+1
end
select * from #temp1

回答5:

可以这样
update T_A
set A = (select A from T_A where id = 1) - isnull((select sum(B) from T_A b where b.id < T_A.id),0),
c = (select A from T_A where id = 1) - (select sum(B) from T_A b where b.id <= T_A.id)