我有一个项目列表,我需要重新排序,没有间隙。它始于:
ID Sequence
123 1
125 2
155 3
158 4
165 6
170 9
我最终需要(注意序列6更改为5,序列9更改为6)
ID Sequence
123 1
125 2
155 3
158 4
165 5
170 6
我已尝试使用此更新声明
UPDATE tblA
SET tblA.Sequence = temp.Sequence
FROM ( SELECT id ,
ROW_NUMBER() OVER ( ORDER BY Sequence, ID ) AS Sequence
FROM dbo.tblA
) AS temp
但我最终还是......
ID Sequence
123 1
125 1
155 1
158 6
165 6
170 6
将select语句拉出更新会产生正确的结果。 将其更改为
UPDATE tblA
SET tblA.Sequence = temp.NewSequence
FROM ( SELECT id ,
ROW_NUMBER() OVER ( PARTITION BY id ORDER BY Sequence, id )
AS NewSequence
FROM dbo.tblA
) AS temp
生成结果
ID Sequence
123 1
125 1
155 1
158 1
165 1
170 1
我做错了什么?
答案 0 :(得分:4)
您需要将重新编号的集合与原始集合中的ID相关联,否则您将使用序列号更新原始ID,以获取临时集合中的其他ID:
UPDATE a
SET a.Sequence = temp.Sequence
FROM
tblA a JOIN
(
SELECT id, ROW_NUMBER() OVER (ORDER BY Sequence, ID) AS Sequence
FROM dbo.tblA
) AS temp ON temp.ID = a.ID