The salary in the middle
- O(2ⁿ) · Legendary
- Full plan
- SQL
- window functions
- grouping
Problem
In Sales the average salary is 2600, but two of its three people earn a good deal less: it's pulled up by Mark, the manager. HR wants a number that a single high salary can't move: the median. You line up the department's salaries from lowest to highest and take the one in the center; with an even number there is no center, and you average the two in the middle.
Show each department's name and the median of its salaries, in that order. For Sales it's 2100. A department with nobody in it doesn't show up, and Carol, who has no department, isn't in any line.
Sort from the highest median to the lowest; if two tie, by the department's name.
What it has to return
These rows, in this order
| name | median |
|---|---|
| Tech | 3000 |
| Design | 2400 |
| Sales | 2100 |
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 dept_id, name, salary
FROM employees
WHERE dept_id IS NOT NULL
ORDER BY dept_id, salaryIt 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 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
- Can I borrow your notes?SQL · subqueries · joins · grouping
- Frank against everyoneSQL · recursion · joins