我想填充序数列,但不想循环记录。有没有办法在单次更新中做到这一点?
CREATE TABLE #Sample
(PrimaryKey Int NOT NULL,
ParentKey Int NOT NULL,
Ordinal Int NULL)
INSERT #Sample (PrimaryKey, ParentKey, Ordinal) VALUES (1, 1, NULL)
INSERT #Sample (PrimaryKey, ParentKey, Ordinal) VALUES (2, 1, NULL)
INSERT #Sample (PrimaryKey, ParentKey, Ordinal) VALUES (3, 1, NULL)
INSERT #Sample (PrimaryKey, ParentKey, Ordinal) VALUES (4, 2, NULL)
INSERT #Sample (PrimaryKey, ParentKey, Ordinal) VALUES (5, 2, NULL)
INSERT #Sample (PrimaryKey, ParentKey, Ordinal) VALUES (6, 3, NULL)
INSERT #Sample (PrimaryKey, ParentKey, Ordinal) VALUES (7, 4, NULL)
INSERT #Sample (PrimaryKey, ParentKey, Ordinal) VALUES (8, 4, NULL)
INSERT #Sample (PrimaryKey, ParentKey, Ordinal) VALUES (9, 5, NULL)
SELECT * FROM #Sample
DROP TABLE #Sample
Ordinal列中的值为1,2,3,1,2,1,1,2,1 我想在每个小组中编号。由“ParentKey”和Ordinal定义的组应按“PrimaryKey”
排序重要!不能依赖PrimaryKey和ParentKey中的值。他们有“漏洞”,没有必要增加1,如我的样本所示..
答案 0 :(得分:2)
假设SQL Server 2005 +:
WITH CTE AS
(
SELECT *,
RN = ROW_NUMBER() OVER(PARTITION BY ParentKey ORDER BY PrimaryKey )
FROM #Sample
)
UPDATE CTE
SET Ordinal = RN