Advanced
Open
Pro
Total Headcount Under Each Manager, Arbitrary Depth
Given an employee table with a self-referencing manager column:
employees
employee_id | name | manager_id
------------+---------+-----------
1 | Priya | NULL -- CEO, no manager
2 | Sam | 1
3 | Ana | 1
4 | Wei | 2
5 | Diego | 4
6 | Grace | 3
For each employee, compute their total headcount underneath them — every direct report, plus every report-of-a-report, recursively, to any depth (not just direct reports). For example, Priya's total should count Sam, Ana, Wei, Diego, and Grace (everyone), while Sam's should count Wei and Diego only.
Write the query and explain why a fixed number of self-joins is not a real solution to this problem, only a workaround that breaks the moment the hierarchy is deeper than however many joins you wrote.
Share this question