Rank within groups with a window function
Question
Show each employee's name, department_id and salary, plus their salary rank inside their own department (1 = highest paid).
employeesid, name, salary, department_id, manager_id, hired_on
departmentsid, name, city
Your query
Ctrl+Enter to run
Result
Expected result
| name | department_id | salary | dept_rank |
|---|---|---|---|
| Priya Nair | 1 | 9200 | 1 |
| Tom Becker | 1 | 8800 | 2 |
| Mei Chen | 1 | 7600 | 3 |
| Hana Kim | 1 | 7300 | 4 |
| Lucas Moreau | 2 | 6800 | 1 |
| Ana Souza | 2 | 6500 | 2 |
| Omar Haddad | 2 | 5600 | 3 |
| Sofia Rossi | 3 | 6100 | 1 |
| Jonas Berg | 3 | 5400 | 2 |
| Aisha Bello | 4 | 4700 | 1 |
| Liam Walsh | 4 | 4300 | 2 |
| Diego Ruiz | 4 | 4100 | 3 |
Hint
RANK() OVER (PARTITION BY ... ORDER BY ...) restarts the ranking for every department.
Show the solution
solution.sql
Run this code
SELECT name, department_id, salary,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS dept_rank
FROM employees;
Why it works
A window function calculates a value for every row while looking at a group of related rows. PARTITION BY makes one window per department, and ORDER BY salary DESC decides who is first.
Common mistake
Unlike GROUP BY, a window function does not collapse rows. Every employee stays in the result; they just get an extra column.