0

我爲我的表創建了一個默認值爲0的列。我想用正確的序列號更新那張表。我可以用Row_Number來做到嗎?基於row_number的更新列

我的表是:

PersonID | Code | Sequence Number 
---------+--------+------------ 
10  | D112 | 0 
10  | D112 | 0 
10  | D112 | 0 
10  | E110 | 0 
10  | E110 | 0 
10  | E110 | 0 
10  | D112 | 0 
10  | D112 | 0 
10  | D112 | 0 
10  | E110 | 0 
10  | E110 | 0 
10  | E110 | 0 

我希望我的表是這樣的:

PersonID | Code | Sequence Number 
---------+--------+------------ 
10  | D112 | 1 
10  | D112 | 1 
10  | D112 | 1 
10  | E110 | 2 
10  | E110 | 2 
10  | E110 | 2 
11  | M490 | 1 
11  | M490 | 1 
11  | M490 | 1 
11  | N550 | 2 
11  | N550 | 2 
11  | N550 | 2 

這是代碼,我有,但不知道這是正確的。

WITH CTE AS (
SELECT 
    t.Sequence Number, 
    ROW_NUMBER() OVER (PARTITION BY t.PersonID, t.Code ORDER BY t.PersonID) AS RN 
FROM Table AS t) 

UPDATE CTE 
SET Sequence Number = RN 
+0

查看select語句是否正確 –

回答

3
DECLARE @Table AS TABLE (PersonId INt, Code CHAR(4), SequenceNumber INT) 

INSERT INTO @Table VALUES (10,'D112',0),(10,'D112',0),(10,'D112',0),(10,'E110',0) 
,(10,'E110',0),(10,'E110',0),(10,'D112',0),(10,'D112',0),(10,'D112',0),(10,'E110',0) 
,(10,'E110',0),(10,'E110',0) 


;WITH CTE AS (
SELECT 
    PersonId 
    ,Code 
    ,SequenceNumber 
    ,DENSE_RANK() OVER (PARTITION BY t.PersonID ORDER BY t.Code) AS RN 
FROM 
    @Table AS t) 


UPDATE cte 
    SET SequenceNumber = RN 

SELECT * 
FROm 
    @Table 

你非常接近只需要做你PARTITION BYORDER BY略有不同,然後用DENSE_RANK()而不是ROW_NUMBER()處理的聯繫。