CTE 获取所有 children 和每个 parent 的嵌套 children

CTE to get all children and nested children of every parent

我陷入了一个不断在脑海中寻找解决方案的问题。

我有一个 users table,有 6k 行,它们是相关的 parent-child。问题是我不仅希望在单个级别 parent-child 关系中获得结果,而且希望在所有级别(直到最后一个 child)每个 userid.

我的 users table.

中有这些数据
UserID | ParentID
1        NULL
2        1
3        1
4        2
5        2
6        5
7        6
8        6
9        NULL

我想要这个数据作为 CTE 的输出。

ParentID  |  UserID
1            1
1            2
1            3
1            4
1            5
1            6
1            7
1            8
2            2
2            4
2            5
2            6
2            7
2            8
3            3
4            4
5            5
5            6
5            7
5            8
6            6
6            7
6            8
7            7
8            8
9            9

注意:ParentID 不仅包括它的 children,还包括它的 children 的 children 和它自己。我正在使用 MSSQL 2019。

在 cte 的第一部分 select 所有以 ownid 作为根 ID 的行。然后在第二部分(联合所有之后)select parentid as rootid.

架构和插入语句:

 create table users (UserID int,  ParentID int);
 insert into users values (1,        NULL);
 insert into users values (2,        1);
 insert into users values (3,        1);
 insert into users values (4,        2);
 insert into users values (5,        2);
 insert into users values (6,        5);
 insert into users values (7,        6);
 insert into users values (8,        6);
 insert into users values (9,        NULL);

查询:

 with cte as
 (
   select userid rootid, userid, parentid from users 
   union all
   select cte.rootid rootid, users.userid, users.parentid from users
   inner join cte on users.parentid=cte.userid
 )
 select rootid parentid,userid from cte
 order by rootid ,userid
 option (maxrecursion 0)

输出:

parentid userid
1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
2 2
2 4
2 5
2 6
2 7
2 8
3 3
4 4
5 5
5 6
5 7
5 8
6 6
6 7
6 8
7 7
8 8
9 9

dbhere