Rank Within the Team
Managers at Kestrel Labs keep asking the wrong version of the same question. They want to know how one of their people sits on pay, and the company-wide answer is useless to them: 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, and every employee has to come back — including Farid Amiri, who is the whole of Marketing and is therefore first on his team by default.
employees — one row per person. department_id is the team they sit on, given as the matching id in departments; salary is annual pay in dollars; hire_date is the day they started, written year-month-day; manager_id is the id of the person they report to, and is NULL for anyone who reports to nobody.
| 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 table already exists in the database — there is nothing to create or load.
Task: Write a query returning three columns, name, department_id and dept_rank (that person's standing by pay inside their own team, 1 being the best paid on that team), one row for every employee. Two teammates on the same salary share a number and the number straight after it is skipped, so a team can read 1, 2, 2, 4. Order the rows by department_id ascending, then by dept_rank ascending. No two teammates are paid the same here, so that fixes the sequence.
Example output — shape only, on invented people. Two teammates on team 21 are paid the same, so they share position 2, position 3 goes unused, and the next person is on 4:
| name | department_id | dept_rank |
|---|---|---|
| Nils Ahlberg | 21 | 1 |
| Mira Solberg | 21 | 2 |
| Otto Brandt | 21 | 2 |
| Yusuf Kaya | 21 | 4 |
| Zoe Marchetti | 24 | 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