在SQL Server中,如何用SQL语句实现:查询某字段的本行记录值如果等于上一行记录值,则本行值+1?

2025-04-14 02:33:04
推荐回答(2个)
回答1:

update a set 记录值=记录值+1
from table as a where exists
(select 1 from table where a.记录值=记录值
group by 记录值 having count(1)>1 and min(id)这个语句你要多运行几次,直到受影响行数为0,因为你的“记录值”重复的不止一次
你可以用group by先查询出重复最大次数,然后用while个循环
或者直接写游标,但是有点繁琐

回答2:

select * into #tmp from 表
update 表 set 表.记录值=记录值+1 from 表 join #tmp on 表.ID=#tmp.ID+1 where 表.记录值=#tmp.记录值
drop table #rmp