SQL Server:具有深度的分层查询

时间:2016-11-19 17:16:00

标签: sql-server tsql

我必须深入展示员工及其经理的姓名。

如果西蒙是高级经理而凯蒂的经理是西蒙,而约翰的经理是凯蒂,那么西蒙的等级将是0,因为他是顶级的,凯蒂的级别将是1和约翰的等级将是2.

我尝试了以下但没有获得所需的输出。请告诉我在代码中应该纠正什么。

我的代码:

Declare @ID INT
SET @ID = 6;

WITH EmployeeCTE AS
(
    SELECT
        ID, Name, MgrID, 0 AS level 
    FROM 
        Employee
    WHERE 
        ID = @ID

    UNION ALL

    SELECT 
        emp.ID, emp.Name, emp.MgrID, level+1 AS level 
    FROM 
        Employee emp
    JOIN 
        EmployeeCTE ON emp.ID = EmployeeCTE.MgrID
)
--select * from EmployeeCTE
SELECT 
    e1.Name, ISNULL(e2.Name, 'Top BOSS') as [Manager Name], 
    e2.level 
FROM
    EmployeeCTE e1 
LEFT JOIN 
    EmployeeCTE e2 ON e1.MgrID = e2.ID 

1 个答案:

答案 0 :(得分:1)

由于这是Node-to-Top,请注意最终选择[Level]

;WITH EmployeeCTE AS
(
    Select ID,Name,MgrID, 0 as level FROM @Employee
    WHERE ID=3
    UNION ALL
    Select r.ID,r.Name,r.MgrID, level+1 as level 
    FROM @Employee r
    JOIN EmployeeCTE p on r.ID = p.MgrID
)
Select e1.Name
      ,ISNULL(e2.Name,'Top BOSS') as [Manager Name]
      ,row_number() over (order by e1.level  desc) as [Level]
 from EmployeeCTE e1 
 left join EmployeeCTE e2 on e1.MgrID=e2.ID 

返回

Name    Manager Name    Level
Simon   Top BOSS        1
Katie   Simon           2
John    Katie           3