【发布时间】:2019-07-25 04:32:04
【问题描述】:
我在表中有父子关系。我想使用父子关系表填充一个新表,该表将包含子级和层次结构中的所有后续父级。
我一直在研究所提供的解决方案,但无法编写能够为我提供所需结果的查询。
以下代码可用于创建表和加载示例数据
create table DemoTable
(
accountid bigint
,parentid bigint
,accountname nvarchar(128)
)
insert DemoTable(accountid,parentid,accountname)
select 1, null, 'Root'
union select 2, 1, 'Child1'
union select 3, 1, 'Child2'
union select 4, 1, 'Child3'
union select 5, 2, 'Child1.1'
union select 6, 2, 'Child1.2'
union select 7, 3, 'Child1.3'
union select 8, 7, 'Child1.3.7'
go
输出应该如下所示
accountid parentid hierarchyLevel
8 7 3
8 3 2
8 1 1
7 3 2
7 1 1
3 1 1
6 2 2
6 1 1
2 1 1
【问题讨论】:
-
我不明白您想要的输出中的
accountid是如何生成的?为什么没有 5 作为accountid? -
我以 8 和 6 帐户 ID 作为样本。但是是的,根据层次结构,输出中也会出现 5。
-
有什么建议吗?
标签: sql sql-server