-
StackOverflow 文件
-
Microsoft SQL Server 教程
-
常用表格表示式
-
員工層次結構
表設定
CREATE TABLE dbo.Employees
(
EmployeeID INT NOT NULL PRIMARY KEY,
FirstName NVARCHAR(50) NOT NULL,
LastName NVARCHAR(50) NOT NULL,
ManagerID INT NULL
)
GO
INSERT INTO Employees VALUES (101, 'Ken', 'Sánchez', NULL)
INSERT INTO Employees VALUES (102, 'Keith', 'Hall', 101)
INSERT INTO Employees VALUES (103, 'Fred', 'Bloggs', 101)
INSERT INTO Employees VALUES (104, 'Joseph', 'Walker', 102)
INSERT INTO Employees VALUES (105, 'Žydrė', 'Klybė', 101)
INSERT INTO Employees VALUES (106, 'Sam', 'Jackson', 105)
INSERT INTO Employees VALUES (107, 'Peter', 'Miller', 103)
INSERT INTO Employees VALUES (108, 'Chloe', 'Samuels', 105)
INSERT INTO Employees VALUES (109, 'George', 'Weasley', 105)
INSERT INTO Employees VALUES (110, 'Michael', 'Kensington', 106)
公用表表示式
;WITH cteReports (EmpID, FirstName, LastName, SupervisorID, EmpLevel) AS
(
SELECT EmployeeID, FirstName, LastName, ManagerID, 1
FROM Employees
WHERE ManagerID IS NULL
UNION ALL
SELECT e.EmployeeID, e.FirstName, e.LastName, e.ManagerID, r.EmpLevel + 1
FROM Employees AS e
INNER JOIN cteReports AS r ON e.ManagerID = r.EmpID
)
SELECT
FirstName + ' ' + LastName AS FullName,
EmpLevel,
(SELECT FirstName + ' ' + LastName FROM Employees WHERE EmployeeID = cteReports.SupervisorID) AS ManagerName
FROM cteReports
ORDER BY EmpLevel, SupervisorID
輸出:
全名 |
EmpLevel |
ManagerName |
KenSánchez |
1 |
空值 |
基思霍爾 |
2 |
KenSánchez |
弗雷德博格斯 |
2 |
KenSánchez |
ŽydreKlybe |
2 |
KenSánchez |
約瑟夫沃克 |
3 |
基思霍爾 |
彼得米勒 |
3 |
弗雷德博格斯 |
山姆傑克遜 |
3 |
ŽydreKlybe |
Chloe Samuels |
3 |
ŽydreKlybe |
喬治韋斯萊 |
3 |
ŽydreKlybe |
邁克爾肯辛頓 |
4 |
山姆傑克遜 |