Rank Employees by Salary Within Department
You're on the data team at Kestrel Labs, and People Ops is opening salary review season. What every manager asks for is the same, and it isn't the payroll figure: they want to see how a person sits against the colleagues they actually work beside. One company-wide list is useless for that. Engineering pay and Marketing pay are set by two different markets, so the best-paid person in Marketing lands mid-table on an all-company list and looks ordinary. The comparison has to restart at every team boundary.
employees — one row per person. department_id is the team they sit on; manager_id points at another employee's id and is empty for the people who lead a team.
| id | name | department_id | salary | hire_date | manager_id |
|---|---|---|---|---|---|
| 1 | Ava Chen | 1 | 145000 | 2021-03-14 | NULL |
| 2 | Ben Ortiz | 1 | 118000 | 2022-06-01 | 1 |
| 3 | Cara Novak | 1 | 121000 | 2023-01-10 | 1 |
| 4 | Deshawn Lee | 2 | 95000 | 2020-09-23 | NULL |
| 5 | Elin Kask | 2 | 88000 | 2022-11-05 | 4 |
| 6 | Farid Amiri | 3 | 76000 | 2023-04-18 | NULL |
| 7 | Grace Kim | 4 | 132000 | 2021-07-30 | NULL |
| 8 | Hugo Silva | 4 | 110000 | 2023-02-14 | 7 |
| 9 | Ines Duarte | 4 | 104000 | 2023-08-01 | 7 |
| 10 | Jonas Weber | 2 | 91000 | 2021-12-19 | 4 |
The tables are already created and filled in the editor — there is nothing to read from input.
Task: Write a query that returns one row for every employee, with name, department_id, salary, and dept_rank — that person's standing by pay inside their own department, 1 being the best paid on that team, 2 the next, and so on. If two teammates are paid exactly the same they share a number, and the number straight after it is skipped, so a team can read 1, 2, 2, 4. Every employee comes back, including the only member of a one-person team, who is a 1. Hand the rows back one department at a time, smallest department_id first, and inside a department the best paid first; two teammates sharing a number are separated by name, alphabetically.
Example output — shape only. These are the opening rows of an invented payroll, not this company's answer; the two teammates on 128000 show the shared number and the skip that follows it.
| name | department_id | salary | dept_rank |
|---|---|---|---|
| Anton Reis | 1 | 150000 | 1 |
| Lena Fournier | 1 | 128000 | 2 |
| Mira Kovac | 1 | 128000 | 2 |
| Rosa Kwan | 2 | 99000 | 1 |
Sign in to solve this problem
Reading problems is free for everyone — solving them (Run, Submit, and tracking what you've solved) needs an account.
Sign in