๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐๐ฒ๐ฟ:
You have 2 minutes to solve this SQL query.
Find the top 3 highest-paid employees in each department.
๐ ๐ฒ: Challenge accepted! ๐ช
SELECT
employee_id,
employee_name,
department,
salary
FROM (
SELECT
employee_id,
employee_name,
department,
salary,
DENSE_RANK() OVER (
PARTITION BY department
ORDER BY salary DESC
) AS salary_rank
FROM employees
) ranked
WHERE salary_rank <= 3
ORDER BY department, salary DESC;
๐ก Explanation:
The query uses the DENSE_RANK() window function to rank employees based on salary within each department.
โข PARTITION BY department creates a separate ranking for every department.
โข ORDER BY salary DESC ranks the highest salary first.
โข DENSE_RANK() assigns the same rank to employees with identical salaries.
โข The outer query returns only employees with a rank of 3 or less.
This question tests your understanding of:
โ
Window Functions
โ
DENSE_RANK()
โ
Top N per Group
โ
Partitioning Data
๐ฏ Expected Output Example
Employee Department Salary Rank
John IT 95,000 1
Alice IT 95,000 1
Bob IT 90,000 2
Mike IT 85,000 3
Sarah HR 80,000 1
๐ Know when to use each ranking function:
โข ROW_NUMBER() โ No ties (unique ranking)
โข RANK() โ Leaves gaps after ties
โข DENSE_RANK() โ No gaps after ties (ideal for Top N with ties)
โค๏ธ React with โค๏ธ for more SQL interview challenges!
Post #2896
4.7K
- โค 22