-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecursive CTE.sql
32 lines (28 loc) · 1.08 KB
/
recursive CTE.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
--recursive CTE to create company's hierarchy tree
select * from Employees
select * from AssociatedPersons
With
EmployeesCTE (EmployeeId, Name, Surname, ManagerId, [Level])
as
(
Select e.ID, ap.Name, ap.Surname, e.ManagerID, 1 --one hardcoded as this is the CEO, to retrieve the CEO record
from Employees e
inner join AssociatedPersons ap
ON e.AssociatedPersonID = ap.ID
where e.ManagerId is null
union all --adding records to first row
Select e.ID, ap.Name, ap.Surname, e.ManagerID, cte.[Level] + 1 --loop and increment by one
from Employees e
inner join AssociatedPersons ap
ON e.AssociatedPersonID = ap.ID
inner join EmployeesCTE cte
ON e.ManagerID = cte.EmployeeId
)
-- SELECT * FROM EmployeesCTE
Select EmpCTE.Name as Name, EmpCTE.Surname as Surname,
ISNULL(MgrCTE.Name, 'CEO,') + ' ' + ISNULL(MgrCTE.Surname, 'no supervisor') as DirectSupervisor,
EmpCTE.[Level]
from EmployeesCTE EmpCTE
left join EmployeesCTE MgrCTE --to display also CEO record that do not have supervisors
on EmpCTE.ManagerId = MgrCTE.EmployeeId
order by [Level] asc