Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Come interrogare e analizzare la gerarchia di elenchi adiacenti usando cte?

I tuoi dati di esempio rendono la domanda più chiara. Potresti raccogliere i livelli di manager mentre scendi:

; 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

Esempio in SQL Fiddle.