TGViewer
Data Analysis Books | Python | SQL | Excel | Artificial Intelligence | Power BI | Tableau | AI Resources Data Analysis Books | Python | SQL | Excel | Artificial Intelligence | Power BI | Tableau | AI Resources @learndataanalysis · 53.3K subscribers
Post #2103 6.46K
✅ SQL Interview Challenge – Filter Top N Records per Group 🧠💾

🧑‍💼 Interviewer: How would you fetch the top 2 highest-paid employees per department?

👨‍💻 Me: Use ROW_NUMBER() with a PARTITION BY clause—it's a window function that numbers rows uniquely within groups, resetting per partition for precise top-N filtering.

🔹 SQL Query:
SELECT *
FROM (
SELECT name, department, salary,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn
FROM employees
) AS ranked
WHERE rn <= 2;


✔ Why it works:
– PARTITION BY department resets row numbers (starting at 1) for each dept group, treating them as mini-tables.
– ORDER BY salary DESC ranks highest first within each partition.
– WHERE rn <= 2 grabs the top 2 per group—subquery avoids duplicates in complex joins!

💡 Pro Tip: Swap to RANK() if ties get equal ranks (e.g., two at #1 means next is #3, but you might get 3 rows); DENSE_RANK() avoids gaps. For big datasets, this scales well in SQL Server or Postgres.

💬 Tap ❤️ for more!
  • ❤ 7
  • 👍 1
More from @learndataanalysis
  1. Sep 23, 2026✅ Types of Machine Learning Algorithms 🤖📊 1️⃣ Supervised Learning Supervised learning me…
  2. Sep 19, 2026🚀 GigaChat 3.5 Reasoning — a new open-source LLM that thinks before it answers. It breaks…
  3. Sep 16, 2026🟠 Part 12 — Dashboard Development • Dashboard layout, Tiled vs Floating, Containers, Devi…
  4. Sep 16, 2026📊 Tableau Learning Roadmap 2026 If you're starting Tableau from scratch, follow this orde…
  5. Sep 6, 2026UNPOPULAR OPINION: Excel is still relevant for data analysis. I am often asked by junior d…
  6. Aug 28, 2026✅ Power BI Basics 📊🚀 👉 Power BI is one of the most popular Business Intelligence BI too…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →