使用SQL Server CTE展平层次结构系列

Jem*_*Jem 2 sql t-sql database sql-server hierarchy

寻找SQL Server CTE示例来创建层次结构,以便我可以输出所有系列,例如展平每个层次结构.例如在家族树中如果root从grand Parent开始我需要每个家庭成员的层次结构列表的列表,其中包含成员详细信息+父级的行详细信息

  child1 row
  child1 +Parent row
  child1 + Grand parent Row

  child2 Row
  child2 + parent row
  child2 + grand parent's row

 and so on
Run Code Online (Sandbox Code Playgroud)
     CREATE TABLE Family(id int NULL,
Name varchar(20) null,  Parent_id int NULL, level int NULL  ) 


INSERT INTO Family VALUES
    (1, 'Grand Parent',NULL,    1),         
    (2, 'Parent'    ,   1,      2),
    (3, 'Child1'    ,   2,      3),
    (4, 'Child2'    ,   2,      3)     

    select * from Family;

id  Name          Parent_id   level
 1  Grand Parent  NULL         1
 2  Parent        1            2
 3  Child1        2            3
 4  Child2        2            3
Run Code Online (Sandbox Code Playgroud)

这就是我现在能做的.父行的详细信息位于第5列和第6列.

with cte as
(
    select ID,Parent_id,level,Name,id as  parent_id,level, 'a' as type
        from family 
        --where ID=3
    union all
    select  f.ID,f.Parent_id,f.level,f.Name,c.id as parent_id,c.level, 'r' as type
    from family f
    inner join cte c
    on f.parent_id=c.id
)
select * from cte order by id
Run Code Online (Sandbox Code Playgroud)

这就是结果应该是什么.(注意第5和6栏)

Child_ID  Parent_id   Child_level   Name    parent_id   level   
1          NULL        1          Grand Parent    1           1  
2          1           2          Parent          2           2  
2          1           2          Parent          1           1  
3          2           3          Child1          1           1  
3          2           3          Child1          2           2  
3          2           3          Child1          3           3   
4          2           3          Child2          4           3  
4          2           3          Child2          2           2   
4          2           3          Child2          1           1   
Run Code Online (Sandbox Code Playgroud)

提前致谢.

muh*_*mud 9

with cte as (
    select ID, Name, level, Parent_id
    from family

    union all

    select cte.ID, cte.Name, cte.level, family.Parent_id
    from cte
    inner join family on cte.Parent_id = family.ID
)
select cte.ID as Child_ID, f2.Parent_ID, cte.level as Child_level, cte.Name, isnull(cte.Parent_id, cte.ID) as parent_ID, isnull(f.level, cte.level) as level
from cte
left outer join family f on cte.Parent_id = f.ID
inner join family f2 on cte.id = f2.ID
order by 1, 5
Run Code Online (Sandbox Code Playgroud)

  • 我已经加倍努力为你完成了这件事.是否接受了答案? (2认同)