多级亲子关系

时间:2018-07-04 11:44:14

标签: sql sql-server tsql

我有一张这样的桌子:

enter image description here

我想这样输出层次结构:

a - c - x1
a - c - x2
a - d - y1
a - d - y2
b - e - z
b - f - q

我稍微搜索了CTE示例,但它们仅列出层次结构的(2,2)组合。如何不依赖于亲子深度而获得此结果?

1 个答案:

答案 0 :(得分:4)

您要使用递归CTE。

以下内容获取所有路径:

with cte as (
      select cast(child as varchar(max)) as path, child, 1 as lev
      from t
      where parent is null
      union all
      select cast(cte.path + ' - ' + t.child as varchar(max)), t.child, lev + 1
      from cte join
           t
           on cte.child = t.parent
     )
select *
from cte;

如果您只想要到终端叶子的路径:

select *
from cte
where not exists (select 1
                  from t
                  where t.parent = cte.child
                 );