Skip to content

Commit 3cb5982

Browse files
committed
Update 00-cte.md
1 parent fda97ea commit 3cb5982

File tree

1 file changed

+19
-12
lines changed

1 file changed

+19
-12
lines changed

docs/en/guides/54-query/00-cte.md

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -301,22 +301,29 @@ WITH RECURSIVE EmployeeHierarchy AS (
301301
-- Recursive query: find employees reporting to the current level
302302
SELECT e.EmployeeID, e.EmployeeName, e.ManagerID
303303
FROM Employees e
304-
INNER JOIN EmployeeHierarchy eh ON e.ManagerID = eh.EmployeeID
304+
INNER JOIN EmployeeHierarchy AS eh2 ON e.ManagerID = eh2.EmployeeID
305305
)
306-
SELECT * FROM EmployeeHierarchy;
306+
SELECT eh.EmployeeID, eh.EmployeeName, eh.ManagerID, m.EmployeeName AS ManagerName
307+
FROM EmployeeHierarchy eh
308+
LEFT JOIN Employees m ON eh.ManagerID = m.EmployeeID
309+
ORDER BY CASE
310+
WHEN eh.EmployeeName = 'Alice' THEN 0 -- Alice goes first
311+
ELSE 1
312+
END,
313+
eh.EmployeeID; -- Then order by EmployeeID
307314
```
308315

309316
The output will list all employees in the hierarchy under Alice:
310317

311318
```sql
312-
┌──────────────────────────────────────────────────────┐
313-
│ employeeid │ employeename │ managerid │
314-
├─────────────────┼──────────────────┼─────────────────┤
315-
1 │ Alice │ NULL
316-
2 │ Bob │ 1
317-
3 │ Charlie │ 1
318-
4 │ David │ 2
319-
5 │ Eve │ 2
320-
6 │ Frank │ 3
321-
└──────────────────────────────────────────────────────┘
319+
┌─────────────────────────────────────────────────────────────────────────
320+
│ employeeid │ employeename │ managerid │ managername │
321+
├─────────────────┼──────────────────┼─────────────────┼──────────────────
322+
1 │ Alice │ NULL NULL
323+
2 │ Bob │ 1 Alice │
324+
3 │ Charlie │ 1 Alice │
325+
4 │ David │ 2 Bob │
326+
5 │ Eve │ 2 Bob │
327+
6 │ Frank │ 3 Charlie │
328+
└─────────────────────────────────────────────────────────────────────────
322329
```

0 commit comments

Comments
 (0)