2016-09-24 65 views
-1

我有一個員工表包含employeeIDnameManagerID - 3列,我想寫一個查詢,顯示namemanagerNamelevel,老闆沒有managerID,其managerID 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查詢?

+4

SQL Server或Oracle?它是針對不同的DBMS。請明確說明。 – gofr1

+1

http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557#285557 –

+0

只是假設這個問題可能存在於SQL服務器和Oracle中。所以如何解決這個問題 – user2575502

回答

1

SQL服務器你可以用遞歸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