sql server - How to uniquely number subnodes of a parent -


i have table so

id               node                  parentid 1                                        0 2                 b                        1 3                 c                        1 4                 d                        2 5                 e                        2 6                 f                        3 7                 g                        3 8                 h                        3  9                                        4 10                j                        4 11                k                        10 12                l                        11 

i need query generate 'position' field order node appears within parent. example below

id               node                  parentid                  positon 1                                        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                                        4                         0 10                j                        4                         1 11                k                        10                        0 12                l                        11                        0 

select  * ,       row_number() on (partition parentid order id) - 1 position    yourtable 

as update query:

update  yt set     position = nr    (         select  *         ,       row_number() on (partition parentid order id) - 1 rn            yourtable         ) yt 

Comments