根据row_number更新列

时间:2016-12-01 22:59:08

标签: sql sql-server sql-server-2012 common-table-expression row-number

我为我的表创建了一个默认值为0的列。我想用正确的序列号更新该表。我可以用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

1 个答案:

答案 0 :(得分: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()来处理这些关系。