我有一张像这样的桌子
ID Node ParentID
1 A 0
2 B 1
3 C 1
4 D 2
5 E 2
6 F 3
7 G 3
8 H 3
9 I 4
10 J 4
11 K 10
12 L 11
我需要一个查询来生成一个'position'字段,其中包含节点在其父节点中出现的顺序。以下示例
ID Node ParentID Positon
1 A 0 0
2 B 1 0
3 C 1 1
4 D 2 0
5 E 2 1
6 F 3 0
7 G 3 1
8 H 3 2
9 I 4 0
10 J 4 1
11 K 10 0
12 L 11 0
答案 0 :(得分:3)
select *
, row_number() over (partition by ParentID order by ID) - 1 as Position
from YourTable
作为更新查询:
update yt
set Position = nr
from (
select *
, row_number() over (partition by ParentID order by ID) - 1 rn
from YourTable
) yt
答案 1 :(得分:2)
要更新原始表中的位置,请将其连接到已建议的语句,作为子查询或CTE:
;with cte (ID, Pos)
as (
select ID, row_number() over (partition by ParentID order by ID) - 1
from [Table]
)
update T
set T.Position = cte.Pos
from [Table] T
join cte on cte.ID = T.ID