2

我有一张这样的桌子

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

我需要一个查询来生成一个“位置”字段,其中节点出现在其父节点中的顺序。下面的例子

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
4

2 回答 2

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
于 2013-07-15T11:33:21.500 回答
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
于 2013-07-15T12:26:21.463 回答