To cover all the sub levels and show Employees and their managers, we need to UNION result set of multi levels all together and go deep inside till find all requested info. Each time that the query needs to go one level deeper, the Level column adds by 1 to show the correct level of employee in organization diagram.
WITH Emp (EmpID, EmpName, ManagerID,
ManagerName, [EmployeeLevel] )
AS
(
SELECT EmpTbl.EmployeeID,
EmpTbl.LastName,
EmpTbl.ReportsTo,
EmpTbl.FirstName+SPACE(1)+EmpTbl.LastName, 1
FROM [Northwind].[dbo].[Employees] as EmpTbl
WHERE ReportsTo IS NULL
UNION ALL
SELECT EmpTbl.EmployeeID,
EmpTbl.LastName,
EmpTbl.ReportsTo,
Mgr.FirstName+SPACE(1)+Mgr.LastName,
[EmployeeLevel] + 1
FROM [Northwind].[dbo].[Employees] as EmpTbl
JOIN Emp
ON Emp.EmpID = EmpTbl.ReportsTO
JOIN [Northwind].[dbo].[Employees] as Mgr
ON EmpTbl.ReportsTO = Mgr.EmployeeID
)
SELECT EmpID,
EmpName,
ManagerID,
ManagerName,
[EmployeeLevel]
FROM Emp
Output:
2 Fuller NULL Andrew Fuller 1
1 Davolio 2 Andrew Fuller 2
3 Leverling 2 Andrew Fuller 2
4 Peacock 2 Andrew Fuller 2
5 Buchanan 2 Andrew Fuller 2
8 Callahan 2 Andrew Fuller 2
6 Suyama 5 Steven Buchanan 3
7 King 5 Steven Buchanan 3
9 Dodsworth 5 Steven Buchanan 3
No comments:
Post a Comment