Return the median salary row or rows for each company
Company: Google
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Write a query returning the median salary row(s) (`id`, `company`, `salary`) of each company. A company with an odd count returns its middle row, and one with an even count returns both middle rows. Order by `company`, then `salary` ascending.
```hint Start with positions
Before writing any SQL, work out which positions are the middle ones in a sorted list of n rows, once for odd n and once for even n.
```
### Input Table(s)
Table `Employee`, primary key `id`:
| Column | Type | Meaning |
|---|---|---|
| id | INT | Employee id, primary key |
| company | VARCHAR(50) | Company the employee works for, never NULL |
| salary | INT | Salary, a positive integer, never NULL |
### Output Contract
Return exactly the columns `id`, `company` and `salary`, one row per median employee, taken unchanged from `Employee`. Do not average the two middle salaries.
Sort by `company` ascending, then `salary` ascending, then `id` ascending. The last key only matters when both middle rows of a company have the same salary.
### Example
`Employee`:
| id | company | salary |
|---|---|---|
| 1 | Acme | 5200 |
| 2 | Acme | 3000 |
| 3 | Acme | 4500 |
| 4 | Acme | 9000 |
| 5 | Acme | 4500 |
| 6 | Birch | 7000 |
| 7 | Birch | 6100 |
| 8 | Birch | 8000 |
| 9 | Birch | 6400 |
| 10 | Cobalt | 5000 |
Expected result:
| id | company | salary |
|---|---|---|
| 5 | Acme | 4500 |
| 9 | Birch | 6400 |
| 6 | Birch | 7000 |
| 10 | Cobalt | 5000 |
Acme has 5 employees. Sorted by salary and then id they are 2, 3, 5, 1, 4, so the middle (third) row is id 5. Ids 3 and 5 share the salary 4500, and the id tiebreak puts id 5 in the middle position. Birch has 4 employees, sorted 7, 9, 6, 8, so the second and third rows (ids 9 and 6) are both returned. Cobalt has one employee, who is its own median.
### Constraints and Clarifications
- `Employee` has at most 1000 rows.
- `salary` is a positive integer. No column is NULL.
- Each company has at least one employee.
- Within a company, rows are ranked by `salary` ascending, then `id` ascending. The middle positions are picked on that ranking, so when several employees share the median salary, only the employees sitting in the middle positions are returned.
Overview: Write a SQL query that returns the median employee row for each company, or both middle rows when the company has an even headcount, ordered by company and salary. It tests window functions, ranking with a deterministic tiebreak, and odd and even position arithmetic.