Me: Sure, let’s use ROW_NUMBER() for this!
SELECT name, salary, department
FROM (
SELECT name, salary, department,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn
FROM employees
) sub
WHERE rn <= 3;
✅ I used a window function to rank employees by salary within each department.
Then filtered the top 3 using a subquery.
🧠 Key Concepts:
- ROW_NUMBER()
- PARTITION BY → resets ranking per department
- ORDER BY → sorts by salary (highest first)
📝 Real-World Tip:
These kinds of queries help answer questions like:
– Who are the top earners by team?
– Which stores have the best sales staff?
– What are the top-performing products per category?
💬 Tap ❤️ for more!