Skip to content

Commit a4d8836

Browse files
[ADD] Recursive organizational structure CTE sample
1 parent 55bab57 commit a4d8836

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
WITH RECURSIVE bosses AS (
2+
-- Init
3+
SELECT id, name, reports_to, 1 AS depth
4+
FROM employees
5+
WHERE id = 1
6+
UNION
7+
-- Recursive
8+
SELECT e.id, e.name, e.reports_to, depth + 1
9+
FROM employees AS e
10+
INNER JOIN bosses AS b ON b.id = e.reports_to
11+
WHERE depth < 6
12+
)
13+
14+
SELECT
15+
b.name,
16+
e.name AS reports_to
17+
FROM bosses AS b
18+
LEFT JOIN employees AS e ON e.id = b.reports_to
19+
ORDER BY b.depth;

0 commit comments

Comments
 (0)