分层查询以返回具有根父级的所有子级

时间:2018-08-26 06:40:17

标签: sql sql-server tsql hierarchical-data

在SQL Server中,我有一个带有示例数据的表,如下所示:

SELECT parent_id,child_id FROM tab a

parent_id   child_id
--------------------
    1           2
    2           3
    3           4
    1           5
    5           6
   12          13

我想用parent_id为所有孩子获取数据,像这样:

Parent_id   Child_id
--------------------
    1          2
    1          3
    1          4
    1          5
    1          6
   12         13

显示所有相关子级的第一个父级。我在下面尝试过

WITH cte_Recursive( Parent, Child, Level ) AS
(
   SELECT T.Parent_id, T.Child_id, 1 AS Level
   FROM tab AS T
   WHERE NOT EXISTS(SELECT * FROM tab AS TI 
                    WHERE T.Child_id = TI.Parent_id)

   UNION ALL

   SELECT TR.Parent_id, TR.Child_id, Level + 1
   FROM tab AS TR
   INNER JOIN cte_Recursive CR ON TR.Child_id = CR.Parent
)
SELECT 
    Parent, Child 
FROM
    (SELECT   
         CR.Parent, CR.Level, iTVF.Child, 
         max_level = MAX(CR.Level) OVER (PARTITION BY NULL)
     FROM 
         cte_Recursive CR
     CROSS APPLY   
         (SELECT   
              CRI.Parent, CRI.Child
          FROM    
              cte_Recursive CRI
          WHERE   
              CR.Level >= CRI.Level) iTVF
    ) AS S
WHERE 
    Level = max_level

但是它没有显示预期的结果

1 个答案:

答案 0 :(得分:3)

以下查询将有所帮助 See working demo here

; with cte as 
(
    select t1.parent_id, t1.child_id
    from tab t1 
    left join tab t2 on t1.parent_id = t2.child_id
    where t2.parent_id is null

    union all

    select c.parent_id, t2.child_id
    from cte c 
    join tab t2 on t2.parent_id = c.child_id
)
select * 
from cte
order by child_id