我有下表test
iD Name ParentId GroupID
-----------------------------
1 1 Null
2 1 Null
3 1 Null
4 7 Null
5 7 Null
6 7 Null
7 9 Null
如何修改它以获得如下列GroupID
:
iD Name ParentId GroupID
------------------------------
1 1 1
2 1 1
3 1 1
4 7 2
5 7 2
6 7 2
7 9 3
答案 0 :(得分:2)
; WITH CTE
AS
(
SELECT iDName, ParentId, GroupID,
DENSE_RANK() OVER (ORDER BY ParentId ASC) RN
FROM Test
)
UPDATE CTE
SET GroupID = RN
Working SQL FIDDLE
答案 1 :(得分:1)
UPDATE test SET GroupID = 1 WHERE ParentId = 1
UPDATE test SET GroupID = 2 WHERE ParentId = 7
UPDATE test SET GroupID = 3 WHERE ParentId = 9