recursively enumerating a subtree
suggest changeWITH RECURSIVE ManagedByJames(Level, ID, FName, LName) AS (
-- start with this row
SELECT 1, ID, FName, LName
FROM Employees
WHERE ID = 1
UNION ALL
-- get employees that have any of the previously selected rows as manager
SELECT ManagedByJames.Level + 1,
Employees.ID,
Employees.FName,
Employees.LName
FROM Employees
JOIN ManagedByJames
ON Employees.ManagerId = ManagedByJames.ID
)
SELECT * FROM ManagedByJames;
WITH RECURSIVE is PostgreSQL syntax; SQL Server omits RECURSIVE. An ORDER BY inside the recursive member is not valid in PostgreSQL and would not control the final order. The rows below are one possible result. James (1) manages John (2) and Michael (3); John manages Johnathon (4).
| Level | ID | FName | LName | |—––|––|———|———| | 1| 1 | James | Smith | | 2| 2 | John | Johnson | | 3| 4 |Johnathon| Smith | | 2| 3 | Michael | Williams|
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents