Their people's people
- O(2ⁿ) · Legendary
- Full plan
- SQL
- recursion
- grouping
Problem
Three people report to Paige, and that's her whole team. With Carol it's different: three report to her, but two of them have people reporting to them, and those people are Carol's too. HR wants each boss's entire team, down to the last level, however many levels there are.
Show the name of each person who has someone below them, how many people they have below them in all, and what all those people's salaries add up to, in that order. The boss's own salary doesn't go into their sum.
Sort from whoever has the most people to whoever has the fewest; if two tie, by name.
What it has to return
These rows, in this order
| name | people | payroll |
|---|---|---|
| Carol | 8 | 22900 |
| Paige | 3 | 8600 |
| Mark | 2 | 4000 |
This is what comes out with the data in the practice database this challenge uses. The column names don’t count, so name yours however you like: what counts is how many there are and the order they come in. Besides this one, the challenge has hidden tests with other data that are revealed when you submit your solution.
You start with this
SQL
SELECT b.name,
COUNT(*) AS people
FROM employees e
JOIN employees b
ON e.boss_id = b.id
GROUP BY b.id, b.nameIt opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.
More O(2ⁿ) challenges
- Use it or lose itSQL · recursion · strings
- Can I borrow your notes?SQL · subqueries · joins · grouping
- Frank against everyoneSQL · recursion · joins
- Not one more, not one lessSQL · window functions · operations
- The chain of commandSQL · recursion · strings
- The emptiest shelfSQL · window functions · dates · sets