【发布时间】:2020-02-13 17:35:04
【问题描述】:
我有一个父母和孩子的自引用表,并且我已经编写了一个递归 CTE,所以我现在有一个父子关系列表,其中包含它们对它们的深度,即它们在哪一代。 现在是否可以将其旋转以在左列中显示曾祖父母的 ID,然后在下一列中显示祖父母,然后是父母,然后是孩子等,请以他们各自的世代作为列标题?
例如您看到我正在插入临时表的数据,我可以得到这个吗?
Gen0 Gen1 Gen2 Gen3 Gen4
1 2 3 4 5
10 20 100 1000
10 20 200
10 30
10 40
create table [#Data] ([ParentId] int, [ChildId] int)
insert [#Data] values
(1, 2)
, (2, 3)
, (3, 4)
, (4, 5 )
, (10, 20)
, (10, 30)
, (10, 40)
, (20, 100)
, (20, 200)
, (200, 1000)
;with [CTE] AS
(
select [A].[ParentId], [A].[ChildId], 1 as [Generation]
from [#Data] [A]
left join [#Data] [B]
on [A].[ParentId] = [B].[ChildId]
where [B].[ChildId] is null
union all
select [D].[ParentId], [D].[ChildId], [Generation] + 1
from [CTE] [C]
join [#Data] [D]
on [C].[ChildId] = [D].[ParentId]
)
select * from [CTE] order by [ParentId], [ChildId]
我正在使用 SQL 2017。 非常感谢您的关注。
【问题讨论】:
标签: sql-server recursion pivot parent-child common-table-expression