Practice 6: Headcount Under Each Manager
HR asks: "For each manager, how many people are under them — not only direct reports but everyone below — and what is their salary total?"
Data
emp(emp_id, emp_nm, mgr_id, sal) is a CTE built with VALUES. mgr_id is the manager's emp_id; the top (CEO) has NULL.
CEO (1)
├─ CTO (2)
│ ├─ Dev Lead (4)
│ │ ├─ Dev A (6)
│ │ │ └─ Intern (10)
│ │ └─ Dev B (7)
│ └─ QA Lead (5)
│ └─ QA A (9)
└─ CFO (3)
└─ Accountant (8)
Requirements
- One row for each employee with at least one subordinate.
depth: 1 for the CEO, 2 for their reports, and so on.sub_cnt: the number of all employees below, not only direct reports (excluding the manager). The CTO has 6: Dev Lead, QA Lead, Dev A, Dev B, QA A and Intern.sub_sal: the totalsalof those employees (excluding the manager).
Result format
| Column | Meaning |
|---|---|
emp_id | Manager number |
emp_nm | Manager name |
depth | Depth |
sub_cnt | Headcount below |
sub_sal | Salary total below |
Sort by emp_id. The result has 6 rows.
My solution
Keep the emp CTE as it is and change the rest. PostgreSQL needs WITH RECURSIVE once any CTE is recursive; Oracle and SQL Server use WITH. The SQL below has no recursion, so it runs on all three DBs.
My solution
WITH emp (emp_id, emp_nm, mgr_id, sal) AS (
SELECT * FROM (VALUES
(1, 'CEO', NULL, 9000), (2, 'CTO', 1, 7000), (3, 'CFO', 1, 6800),
(4, 'Dev Lead', 2, 5000), (5, 'QA Lead', 2, 4800), (6, 'Dev A', 4, 3500),
(7, 'Dev B', 4, 3300), (8, 'Accountant', 3, 3000), (9, 'QA A', 5, 3100),
(10, 'Intern', 6, 2000)
) AS t (emp_id, emp_nm, mgr_id, sal)
)
SELECT m.emp_id, m.emp_nm, COUNT(*) AS direct_cnt, SUM(e.sal) AS direct_sal
FROM emp m
JOIN emp e ON e.mgr_id = m.emp_id
GROUP BY m.emp_id, m.emp_nm
ORDER BY m.emp_id
Hints
- The starting SQL counts direct reports only. To count everyone below, build (manager, subordinate) pairs recursively: the anchor part is the direct
(mgr_id, emp_id)pairs, and the recursive part adds the reports of the previous step's subordinates (Recursive WITH, Walking a hierarchy). - For the depth, build one more recursive CTE going from the top down, and join it.
- Grouping the pairs by manager gives the headcount and the salary total.