我的员工表包含employeeID
,name
和ManagerID
- 3列,我想编写一个查询来显示name
,managerName
和level
,Boss没有managerID
,managerID is null
见下表结构
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)
我想得到的效果:
如何编写SQL查询?
答案 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