我有一张叫雇员的表。请参考下表,我希望员工向哪个经理报告的级别。我不知道会有什么逻辑。我已经使用过CTE,但没有得到预期的结果。在这种情况下,请帮助我以获得预期的结果。
表员工
EmpID. EmpName. ManagerID
1 A Null
2 B 1
3 C 1
4 D 2
5 E 3
6 F 4
7 G 5
8 H 5
预期结果
EmpName. ManagerName Level
A Null 1
B A 2
C A 2
D B 3
E C 4
F D 5
G E 6
H E 6
答案 0 :(得分:0)
假设您正在使用Sql Server
,则可以使用以下代码进行操作:
WITH cte (EmpId, EmpName, ManagerName, LEVEL) AS (
SELECT EmpId, EmpName, CAST('' AS VARCHAR) as ManagerName, 1 AS LEVEL
FROM Employee
WHERE ManagerId IS NULL
UNION ALL
SELECT e1.EmpId, e1.EmpName, CAST(cte.EmpName AS VARCHAR) ManagerName, (cte.LEVEL + 1) AS LEVEL
FROM Employee e1
JOIN cte ON e1.ManagerId = cte.EmpId
)
SELECT EmpName, ManagerName, LEVEL FROM cte
ORDER BY EmpName
请注意,您需要修改预期输出中的级别。例如,对于员工H
,层次结构为H => E => C => A
,这表明其级别为4
。正确的级别如下:
EmpName ManagerName Level
A 1
B A 2
C A 2
D B 3
E C 3
F D 4
G E 4
H E 4
答案 1 :(得分:0)
递归CTE在Postgresql中工作。
一旦获得了每个员工的所有级别,就可以将其分组以获取最大级别。
WITH RECURSIVE RCTE AS
(
SELECT
EmpID AS BaseEmpID,
ManagerID AS BaseManagerID,
1 AS Lvl,
EmpID,
ManagerID
FROM employee
UNION ALL
SELECT
c.BaseEmpID,
c.BaseManagerID,
Lvl + 1,
m.EmpID,
m.ManagerID
FROM RCTE c
JOIN employee m
ON m.EmpID = c.ManagerID
)
, EMPLEVELS AS
(
SELECT
BaseEmpID,
BaseManagerID,
MAX(Lvl) AS Level
FROM RCTE
GROUP BY BaseEmpID, BaseManagerID
)
SELECT
e.EmpName,
m.EmpName AS ManagerName,
elvl.Level
FROM EMPLEVELS elvl
JOIN employee e ON e.EmpID = elvl.BaseEmpID
LEFT JOIN employee m ON m.EmpID = elvl.BaseManagerID
ORDER BY elvl.BaseEmpID;
返回:
empname managername level
A NULL 1
B A 2
C A 2
D B 3
E C 3
F D 4
G E 4
H E 4
如果删除了RECURSIVE单词,则该查询将在MS Sql Server中工作。
答案 2 :(得分:0)
我认为您想要一个简单的join
:
select e.name, em.name as manager_name
from employees e left join
employees em
on e.managerId = em.empId;