更新表中的列

时间:2014-04-24 12:12:08

标签: sql sql-server

我有下表test

Id ParentId DisplayingOrder GrpId 
1  NULL        NULL         NULL
2  NULL        NULL         NULL
3  NULL        NULL         NULL
4  NULL        NULL         NULL

我需要有类似的东西:

    Id ParentId DisplayingOrder GrpId 
    23  NULL       1            21
    24  NULL       1            22
    25  NULL       1            23
    26  NULL       1            24

我试过这个

; WITH CTE 
AS
 (
 SELECT [Id],[ParentId] , [GrpId],DisplayingOrder 
        ,DENSE_RANK() OVER (ORDER BY [ParentId] ASC) RN1
        ,ROW_NUMBER() OVER (PARTITION BY [ParentId] ORDER BY [ParentId]) RN2
  FROM [dbo].[test]
 )
UPDATE CTE 
SET  [GrpId]         = RN1
    ,DisplayingOrder = RN2

但它返回结果:

      Id ParentId DisplayingOrder GrpId 
        23  NULL       21            1
        24  NULL       22            1
        25  NULL       23            1
        26  NULL       24            1

1 个答案:

答案 0 :(得分:0)

在此部分中,将RN1RN2交换:

SET  [GrpId]         = RN2
    ,DisplayingOrder = RN1