我正在尝试重新排序数据库中的某些记录。我想出了这个剧本:
UPDATE r
SET r.DisplaySequence = temp.DisplaySequence
FROM
SomeTable r JOIN
(
SELECT RecordID, ROW_NUMBER() OVER (ORDER BY DisplaySequence, InsertedOn) AS DisplaySequence
FROM dbo.SomeTable WHERE FacCode IS NULL AND UserID IS NULL
) AS temp ON temp.RecordID = r.RecordID
WHERE FacCode IS NULL AND UserID IS NULL
这将使用新值更新DisplaySequence
列,并尊重当前记录可能包含的任何订单。
但是,每当DisplaySequence
更改时,我都需要“重置”RecordCategoryID
。
所以,如果我有这些数据:
RecordID | RecordCategoryID | DisplaySequence --------------------------------------------- 1 1 1 2 1 2 3 1 3 4 2 4 5 2 5 6 2 6
由于DisplaySequence
已更改,RecordCategoryID
应该从最后3条记录的1重新开始,但我无法弄清楚如何“重置”ROW_NUMBER()
值?
答案 0 :(得分:1)
詹姆斯Z在评论中回答:
使用 row_number()
partition by
条款的over()
部分
UPDATE r
SET r.DisplaySequence = temp.DisplaySequence
FROM SomeTable r
JOIN (
SELECT RecordID
, row_number() over (
partition by RecordCategoryId
order BY DisplaySequence, InsertedOn
) AS DisplaySequence
FROM dbo.SomeTable
WHERE FacCode IS NULL
AND UserID IS NULL
) AS temp ON temp.RecordID = r.RecordID
WHERE FacCode IS NULL
AND UserID IS NULL