Skip to content
BytePatterns

Top Two Earners per Department

MediumSQL#window-function#top-n-per-group~25m

Problem

A table employee(id, name, dept, salary) holds one row per person. For each department, return everyone whose salary is one of the two highest distinct salaries in that department, so people who tie are all kept. Return columns dept, name and salary, sorted by department, then salary from high to low, then name.

Examples

Input:  employee = [(1, "Ana", "eng", 120), (2, "Ben", "eng", 90), (3, "Cleo", "eng", 130), (4, "Dev", "ops", 95), (5, "Eve", "ops", 80), (6, "Finn", "ops", 100)]
Output: [("eng", "Cleo", 130), ("eng", "Ana", 120), ("ops", "Finn", 100), ("ops", "Dev", 95)]
Input:  employee = [(1, "Ana", "eng", 120), (2, "Ben", "eng", 120), (3, "Cleo", "eng", 110), (4, "Dev", "eng", 100)]
Output: [("eng", "Ana", 120), ("eng", "Ben", 120), ("eng", "Cleo", 110)]
Why:    Ana and Ben share the top salary, so the two highest distinct salaries are 120 and 110
Input:  employee = [(1, "Ana", "eng", 120), (2, "Gus", "hr", 70)]
Output: [("eng", "Ana", 120), ("hr", "Gus", 70)]
Why:    edge case, a department with one person returns that person

Hints

0 / 3

Stuck on the idea rather than the code? Query Execution Order covers it.