我需要获取一个查询,从一个特定的经理开始一直显示下属。让我们说我有这种结构,我需要让所有员工从ManagerId = 1
开始EmployeeId ManagerId
2 1
3 1
4 3
5 3
6 4
我需要获得ManagerId的查询结果,并直接向他下属的员工及其下属报告。
例如,使用SQL Server 2014:
CREATE TABLE #Pepe (EmployeeId INT, ManagerId int)
INSERT INTO [#Pepe] ( [EmployeeId], [ManagerId] ) VALUES (2, 1)
INSERT INTO [#Pepe] ( [EmployeeId], [ManagerId] ) VALUES (3, 1)
INSERT INTO [#Pepe] ( [EmployeeId], [ManagerId] ) VALUES (4, 3)
INSERT INTO [#Pepe] ( [EmployeeId], [ManagerId] ) VALUES (5, 3)
INSERT INTO [#Pepe] ( [EmployeeId], [ManagerId] ) VALUES (6, 4)
现在我得到了CTE
;WITH relation AS
(
SELECT 1 as EmployeeId, 0 AS LEVEL
UNION ALL
SELECT r.EmployeeId, LEVEL + 1 AS LEVEL
FROM (SELECT EmployeeId, ManagerId FROM #Pepe) r
INNER JOIN relation T
ON r.ManagerId = T.EmployeeId
WHERE r.ManagerId <> r.EmployeeId
)
SELECT DISTINCT EmployeeId, LEVEL FROM relation
我的CTE结果如下:
EmployeeId LEVEL
1 0
2 1
3 1
4 2
5 2
6 3
此结果从一个特定员工开始,该员工为1(在CTE上是硬编码的),现在我只需要直接报告,Level = 1以及也是0级员工ID 1,2和3。
这很好,现在我需要的是每个员工ID(0级和1级),我需要得到这个结果:
EmployeeId ManagerId
1 1
2 1
3 1
4 1
5 1
6 1
2 2
3 3
4 3
5 3
6 3
正如您所看到的,Manager ID包含0级和1级的员工,对于每个员工,我基本上都会调用CTE来让所有员工失望,例如ManagerId = 2没有下属,但我需要无论如何要数。有没有一种有效的方法来做到这一点?我正在使用交叉应用将CTE放入内联函数中,但我遇到了性能问题。
答案 0 :(得分:0)
我想我找到了解决方案,我想就此发表意见。
;WITH relation AS
(
SELECT 1 AS ManagerId, 1 as EmployeeId, 0 AS LEVEL UNION
SELECT 2 AS ManagerId, 2 as EmployeeId, 0 AS LEVEL UNION
SELECT 3 AS ManagerId, 3 as EmployeeId, 0 AS LEVEL
UNION ALL
SELECT t.[ManagerId], r.EmployeeId, LEVEL + 1 AS LEVEL
FROM (SELECT EmployeeId, ManagerId FROM #Pepe) r
INNER JOIN relation T
ON r.ManagerId = T.EmployeeId
WHERE r.ManagerId <> r.EmployeeId
)
SELECT DISTINCT EmployeeId, [ManagerId] FROM relation ORDER BY 2
答案 1 :(得分:0)
您几乎拥有了它。只需从#Pepe表中选择不同的经理,而不是手动执行3个select语句
DECLARE @Pepe TABLE (EmployeeId INT, ManagerId int)
INSERT INTO @Pepe ( [EmployeeId], [ManagerId] ) VALUES (1, 1)
INSERT INTO @Pepe ( [EmployeeId], [ManagerId] ) VALUES (2, 1)
INSERT INTO @Pepe ( [EmployeeId], [ManagerId] ) VALUES (3, 1)
INSERT INTO @Pepe ( [EmployeeId], [ManagerId] ) VALUES (4, 3)
INSERT INTO @Pepe ( [EmployeeId], [ManagerId] ) VALUES (5, 3)
INSERT INTO @Pepe ( [EmployeeId], [ManagerId] ) VALUES (6, 4)
;WITH relation (ManagerId, EmployeeId, LEVEL)
AS
(
SELECT DISTINCT ManagerId, ManagerId AS EmployeeId, 0 AS LEVEL
FROM @Pepe
UNION ALL
SELECT t.[ManagerId], r.EmployeeId, LEVEL + 1 AS LEVEL
FROM @Pepe r
INNER JOIN relation T
ON r.ManagerId = T.EmployeeId
WHERE r.ManagerId <> r.EmployeeId
)
SELECT DISTINCT EmployeeId, ManagerId, LEVEL FROM relation ORDER BY ManagerId