Exercise 1
advancedQuestion
Rank employees by salary within each department.
Table Schema
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100),
salary DECIMAL(10,2),
department VARCHAR(50)
);Show Solution
Solution
1SELECT
2 name,
3 department,
4 salary,
5 RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS salary_rank
6FROM employees;Expected Output
| name | department | salary | salary_rank | |---|---|---|---| | Alice | Engineering | 80000 | 1 | | Bob | Engineering | 70000 | 2 |
Explanation
PARTITION BY divides rows into groups. ORDER BY determines ranking order. RANK() gives same rank to ties.