获取 parent/children 其中 parent 数字并不总是匹配

Get parent/children where parent numbers don't always match

我在将所有相关项目汇总到一个结果集中时遇到问题。

在这种情况下,我们有一个主控 ParentPart (901359),其组件是相关的。我们也可以有 parent 部分的组件 (340804, 340801, 340850)

下面的数据是我正在处理的

ParentPart  Component
---------------------
901359      340804
340804      340801
340801      340850
340850      333000

我想要得到的是这个结果,或者把所有相关的组件都拿到 roll-up

ParentPart  Component
----------------------
901359      340804
901359      340801
901359      340850
901359      333000

下面是测试代码。

CREATE TABLE #Hierarchy 
(
    ParentPart VARCHAR(15),
    Component VARCHAR(15)
)

INSERT INTO #Hierarchy (ParentPart, Component)
VALUES 
  ('901359','340804'),
  ('340804','340801'),
  ('340801','340850'),
  ('340850','333000')

 SELECT *
 FROM #Hierarchy

 DROP TABLE #Hierarchy

我试过递归 CTE,但它没有给我想要的结果,因为 parent 部分不完全相同。

有什么指点吗?

以下递归 CTE 将完成工作:

with hier as (
select ParentPart as MainPart, ParentPart, Component from #Heirarchy
union all
select hier.MainPart, p.ParentPart, p.Component 
from hier 
join #Heirarchy as p
on p.ParentPart = hier.Component 
)
select MainPart, Component from hier where MainPart = '901359';

这是一个典型的递归查询。在这种情况下,您可以从顶部到底部遍历树:

with cte as (
    select parentpart, component, 1 lvl  from #Hierarchy
    union all
    select c.parentpart, h.component, lvl + 1
    from cte c
    inner join #Hierarchy h on h.parentpart = c.component
)
select parentpart, component
from cte c 
where c.lvl = (select max(c1.lvl) from cte c1 where c1.component = c.component)

递归通用table表达式生成树路径,同时跟踪每个节点的级别;然后外部查询在每个节点的顶​​部父级上进行过滤。

Demo on DB Fiddle:

parentpart | component
:--------- | :--------
901359     | 340804   
901359     | 340801   
901359     | 340850   
901359     | 333000