修改表中的列

时间:2014-04-18 11:07:52

标签: sql

我有以下表格测试

iD Name    ParentId   GroupID  DisplayingOrder
 ---------------------------------------------
    1            1        1      Null
    2            1        1      Null
    3            1        1      Null
    4            7        2      Null
    5            7        2      Null
    6            7        2      Null
    7            9        3      Null

如何修改它以获取

iD Name    ParentId   GroupID  DisplayingOrder
 ---------------------------------------------
    1            1        1      1
    2            1        1      2
    3            1        1      3
    4            7        2      1
    5            7        2      2
    6            7        2      3
    7            9        3      1

逻辑:对同一GroupID递增DisplaysOrder

4 个答案:

答案 0 :(得分:2)

您可以在一个查询中执行这两个更新,而不需要在两个语句中将其分解。见下文:

; WITH CTE 
AS
 (
 SELECT iDName, ParentId, GroupID,DisplayingOrder 
        ,DENSE_RANK() OVER (ORDER BY ParentId ASC) RN1
        ,ROW_NUMBER() OVER (PARTITION BY ParentId ORDER BY ParentId) RN2
  FROM TEST
 )
UPDATE CTE 
SET  GroupID         = RN1
    ,DisplayingOrder = RN2

Sql Fiddle

此外,如果您可以查看SQL SERVER RANKING FUNCTIONS,它将真正帮助您:)

答案 1 :(得分:1)

这不是先前问题的完全重复。但是一种非常类似的方法可以起作用:

WITH toupdate AS
      (SELECT iDName, ParentId, GroupID,
              row_number() over (partition by groupid order by idName) as newDisplayingOrder
       FROM test t
      )
UPDATE toupdate
    SET DisplayingOrder = newDisplayingOrder;

您可以一步完成这两项任务:

WITH toupdate AS
      (SELECT t.*,
              dense_rank() over (order by ParentId) as newGroupId,
              row_number() over (partition by groupid order by idName) as newDisplayingOrder
       FROM test t
      )
UPDATE toupdate
    SET GroupId = newGroupId,
        DisplayingOrder = newDisplayingOrder;

答案 2 :(得分:0)

使用此查询并更新具有不同iD名称的所有行

Update test set DisplayingOrder = 1 where iD Name = 1;

答案 3 :(得分:0)

WITH CTE_View AS       (选择t1。*,               dense_rank()over(由ParentId排序)为newGroupId,               row_number()over(由idid分组groupid)作为newDisplayingOrder        FROM tab t1       ) 更新CTE_View     SET GroupId = newGroupId,         ShowingOrder = newDisplayingOrder;