Write a query that returns, for every manager, the **total number of
people under them — direct reports and** indirect reports (their
reports' reports, and so on). Employees with nobody under them should not
appear at all.
Table: `employees`
| id | name | manager_id |
|---|---|---|
| 1 | CEO | NULL |
| 2 | VP Eng | 1 |
| 3 | VP Sales | 1 |
| 4 | Eng Manager | 2 |
| 5 | Engineer A | 4 |
| 6 | Engineer B | 4 |
| 7 | Sales Rep | 3 |
Expected output (columns: ancestor_id, total_reports), ordered byancestor_id:
1|6
2|3
3|1
4|2Hint — first build every
(ancestor_id, descendant_id)pair thehierarchy implies (a self-join-like recursive CTE), then
GROUP BYthe ancestor to count.
Sample tests