How to query and parse adjacent list hierarchy using cte?

瘦欲@ 提交于 2019-12-04 16:57:34

Your example data makes the question clearer. You could collect the manager levels as you descend:

; with  Tree as
        (
        SELECT  empid
        ,       mgrid
        ,       1 as lv
        ,       1 as level1
        ,       null as level2
        ,       null as level3
        ,       null as level4
        ,       null as level5
        FROM    Employees
        WHERE   mgrid IS NULL 
        UNION ALL
        SELECT  E.empid
        ,       E.mgrid
        ,       T.lv + 1
        ,       T.level1
        ,       case when T.lv = 1 then E.empid else t.level2 end
        ,       case when T.lv = 2 then E.empid else t.level3 end
        ,       case when T.lv = 3 then E.empid else t.level4 end
        ,       case when T.lv = 4 then E.empid else t.level5 end
        FROM    Employees AS E
        JOIN    Tree T
        ON      E.mgrid = T.empid
        )
select  *
from    Tree

Example at SQL Fiddle.

MatBailie
;WITH Tree (empid, level, level1, level2, level3, level4, level5)
AS (

SELECT empid, 1, empid, NULL, NULL, NULL, NULL
FROM Employees
WHERE mgrid IS NULL 

UNION ALL

SELECT E.empid, T.level + 1,
       CASE WHEN T.level+1 = 1 THEN E.empid ELSE T.level1 END,
       CASE WHEN T.level+1 = 2 THEN E.empid ELSE T.level2 END,
       CASE WHEN T.level+1 = 3 THEN E.empid ELSE T.level3 END,
       CASE WHEN T.level+1 = 4 THEN E.empid ELSE T.level4 END,
       CASE WHEN T.level+1 = 5 THEN E.empid ELSE T.level5 END 
FROM Employees AS E
JOIN Tree T
ON E.mgrid= T.empid
)
SELECT empid, level, level1, level2, level3, level4, level5
FROM Tree

With a pivot?

;WITH Tree (empid, mgrid, lv)
AS (

SELECT empid, mgrid, 1
FROM @Employees
WHERE mgrid IS NULL 

UNION ALL

SELECT E.empid, E.mgrid, lv + 1
FROM @Employees AS E
JOIN Tree
ON E.mgrid= Tree.empid
)
select *
from
Tree
pivot 
(count(empid) for lv in ([1],[2],[3],[4],[5]))p
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!