One Level At A Time
employees:
| id | manager_id |
|---|---|
| 1 | NULL |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 2 |
| 6 | 4 |
WITH RECURSIVE chain(id, depth) AS (
SELECT id, 0
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, c.depth + 1
FROM employees e
JOIN chain c ON e.manager_id = c.id
)
SELECT depth, count(*) FROM chain GROUP BY depth ORDER BY depth;
What is the output?
Sign in to answer questions and track your progress
Sign In