自我加入运作

时间:2016-09-24 07:44:08

标签: sql-server oracle

我的员工表包含employeeIDnameManagerID - 3列,我想编写一个查询来显示namemanagerNamelevel,Boss没有managerIDmanagerID is null 见下表结构

enter image description here

CREATE TABLE #employee (
    EmployeeID int, 
    [Name] nvarchar(50), 
    ManagerID int
)

INSERT INTO #employee VALUES
(1,'Tom',2),
(2,'Josh',NULL),
(3,'Mike',2),
(4,'John',3),
(5,'Pam',1),
(6,'Mary',3),
(7,'James',1),
(8,'Sam',5),
(9,'Simon',1)

我想得到的效果:

enter image description here

如何编写SQL查询?

1 个答案:

答案 0 :(得分:1)

SQL Server 中,您可以使用递归CTE执行此操作:

;WITH rec AS (
SELECT  EmployeeID, 
        [Name], 
        ManagerID,
        1 as [Level]
FROM employee 
WHERE ManagerID IS NULL
UNION ALL
SELECT  e.EmployeeID, 
        e.[Name], 
        e.ManagerID,
        r.[Level] + 1
FROM employee e
INNER JOIN rec r
    ON e.ManagerID = r.EmployeeID
)

SELECT  r.[Name] as Employee,
        COALESCE(e.[Name],'Super Boss') as Manager,
        r.[Level]
FROM rec r
LEFT JOIN employee e
    ON e.EmployeeID = r.ManagerID

输出:

Employee    Manager     Level
Josh        Super Boss  1
Tom         Josh        2
Mike        Josh        2
John        Mike        3
Mary        Mike        3
Pam         Tom         3
James       Tom         3
Simon       Tom         3
Sam         Pam         4