This SQL query ranks employees within each department based on their salary in descending order. It returns the department ID, employee ID, salary, and the rank of each employee within their respective department.
SELECT department_id,
employee_id,
salary,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rank
FROM employees
ORDER BY department_id, rank;
department_id: Retrieves the ID of the department.employee_id: Retrieves the ID of the employee.salary: Retrieves the salary of the employee.RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rank: This is the window function calculating the rank of each employee within their department.RANK(): This is the window function used to assign ranks to rows within each partition.OVER: Defines the window of rows for the function.
PARTITION BY department_id: Divides the result set into partitions based on department_id. Each department is treated as a separate group.ORDER BY salary DESC: Orders the rows within each partition by salary in descending order, assigning higher ranks to higher salaries.FROM employees: Specifies the table from which to retrieve the data.ORDER BY department_id, rank: Orders the final result set first by department_id and then by rank within each department.Initial State: Assume the employees table has the following
| department_id | employee_id | salary |
|---|---|---|
| 1 | 101 | 50000 |
| 1 | 102 | 60000 |
| 1 | 103 | 60000 |
| 2 | 201 | 45000 |
| 2 | 202 | 55000 |
| 2 | 203 | 50000 |
Processing Each Department:
Final Output:
| department_id | employee_id | salary | rank |
|---|---|---|---|
| 1 | 102 | 60000 | 1 |
| 1 | 103 | 60000 | 1 |
| 1 | 101 | 50000 | 3 |
| 2 | 202 | 55000 | 1 |
| 2 | 203 | 50000 | 2 |
| 2 | 201 | 45000 | 3 |