如何在特定列更改时重置值?

时间:2017-03-27 16:06:23

标签: sql sql-server sql-server-2012

我正在尝试重新排序数据库中的某些记录。我想出了这个剧本:

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()值?

1 个答案:

答案 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