Skip to content
BytePatterns

Department With the Highest Average Pay

MediumSQL#group-by#cte#ties~20m

Problem

A table employee(id, name, dept, salary) holds one row per person. Write a query that returns the department with the highest average salary, together with that average rounded to two decimals, as columns dept and avg_salary. When several departments tie for the highest average, return all of them, sorted by department.

Examples

Input:  employee = [(1, "Ana", "eng", 120), (2, "Cleo", "eng", 130), (3, "Dev", "ops", 95), (4, "Finn", "ops", 100), (5, "Gus", "hr", 70)]
Output: [("eng", 125.0)]
Why:    the averages are eng 125, ops 97.5 and hr 70
Input:  employee = [(1, "Ana", "eng", 100), (2, "Ben", "eng", 110), (3, "Dev", "ops", 105)]
Output: [("eng", 105.0), ("ops", 105.0)]
Why:    both departments average 105, so both come back
Input:  employee = [(1, "Ana", "sales", 100), (2, "Ben", "sales", 100), (3, "Cy", "sales", 101)]
Output: [("sales", 100.33)]
Why:    edge case, 301 / 3 is rounded to two decimals only for display

Hints

0 / 3

Stuck on the idea rather than the code? Aggregations & GROUP BY covers it.