The chain of command
- O(2ⁿ) · Legendary
- Full plan
- SQL
- recursion
- strings
Problem
Someone new joins HR and asks for the org chart. Nobody has ever drawn one: all there is to go on is employees, where each person's row says who their boss is and nothing more.
For each person, show their name, their level, and their chain of command, in that order. The level is how many bosses they have above them: someone with none, like Carol, is at 0. The chain goes in a single cell, from the very top down to the person, with > between one name and the next: Samuel's is Carol > Paige > Samuel, and Carol's is Carol.
Sort by the chain, as the text it is: everyone lands right under their boss, and the org chart draws itself.
What it has to return
These rows, in this order
| name | level | chain |
|---|---|---|
| Carol | 0 | Carol |
| Grace | 1 | Carol > Grace |
| Mark | 1 | Carol > Mark |
| Nicole | 2 | Carol > Mark > Nicole |
| Rachel | 2 | Carol > Mark > Rachel |
| Paige | 1 | Carol > Paige |
| Frank | 2 | Carol > Paige > Frank |
| Lydia | 2 | Carol > Paige > Lydia |
| Samuel | 2 | Carol > Paige > Samuel |
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 e.name, b.name AS boss
FROM employees e
LEFT JOIN employees b
ON e.boss_id = b.idIt 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
- The emptiest shelfSQL · window functions · dates · sets
- The salary in the middleSQL · window functions · grouping
- The store on a streakSQL · window functions · dates
- The Winters oneSQL · recursion · strings · window functions
- Their people's peopleSQL · recursion · grouping
- Use it or lose itSQL · recursion · strings