【发布时间】:2016-08-10 18:07:22
【问题描述】:
我无法弄清楚如何使用递归 CTE 对结果进行递归排序。这就是我的意思(这是一个简化的数据集):
我有这个作为输入:
declare @sections table (id int, parent int);
insert into @sections values (1, 1);
insert into @sections values (2, 2);
insert into @sections values (3, 2);
insert into @sections values (4, 2);
insert into @sections values (5, 4);
insert into @sections values (6, 1);
insert into @sections values (7, 6);
insert into @sections values (8, 6);
insert into @sections values (9, 6);
insert into @sections values (10, 9);
-- hierarchical view
--1
-- 6
-- 7
-- 8
-- 10
-- 9
--2
-- 3
-- 4
-- 5
我想要这个作为输出 编辑:行的顺序是这里的重要部分
-- id parent depth
-- 1 1 0
-- 6 1 1
-- 7 6 2
-- 8 6 2
-- 10 8 3
-- 9 6 2
-- 2 2 0
这是我能做的最好的:
with section_cte as
(
select id, parent, 0 'depth' from @sections where id = parent
union all
select cte.id, cte.parent, depth + 1
from @sections s join section_cte cte on s.parent = cte.id where s.id <> s.parent
)
select *from section_cte
谁能帮我调整这个查询以获得我需要的东西?
谢谢!
【问题讨论】:
-
你能解释一下输出吗
-
你为什么选择根级项目是它们自己的父母的方案?这些父母通常是空的。
-
@MartinSmith 在我们的系统中,根级别是 id = parent。这就是为什么模拟数据是这样的原因
-
@TheGameiswar 输出中的行顺序就像是深度优先递归遍历树一样。
标签: tsql recursion common-table-expression