๐ง SQL Interview Question (Top-N per Group + Tie Handling - Tricky)
๐
scores(student_id, subject, marks)
โ Ques :
๐ Find students who scored the highest marks in each subject.
๐ If multiple students have the same top score, include all of them (handle ties).
๐งฉ How Interviewers Expect You to Think
โข Group data by subject ๐
โข Identify highest marks within each group
โข Handle ties correctly (donโt lose rows)
โข Use window functions (RANK vs ROW_NUMBER)
๐ก SQL Solution
SELECT
student_id,
subject,
marks
FROM (
SELECT
scores.student_id,
scores.subject,
scores.marks,
RANK() OVER (
PARTITION BY scores.subject
ORDER BY scores.marks DESC
) AS rnk
FROM scores
) ranked_scores
WHERE ranked_scores.rnk = 1;
๐ฅ Why This Question Is Powerful
โข Tests Top-N per group (very common pattern) ๐ง
โข Checks understanding of RANK vs ROW_NUMBER
โค๏ธ React if you want more real interview-level SQL questions ๐
Post #2387
5.15K
- โค 15