Skip to content

Instantly share code, notes, and snippets.

@megpay
Last active June 23, 2020 07:28
Show Gist options
  • Save megpay/1228f8cb5aa186aad2a10906c27378c3 to your computer and use it in GitHub Desktop.
Save megpay/1228f8cb5aa186aad2a10906c27378c3 to your computer and use it in GitHub Desktop.
Top Employee Salary by Department
/*
Given 2 tables in a MySQL database, Employee and Department, find the employees (including ties) with the highest
salaries for each department.
Employee table:
Id (auto incremented integer)
Name (Varchar, employee name)
DepartmentId (integer and key to Department table)
Salary (Integer)
Department table:
Id (auto incremented integer
Name (varchar, department name)
*/
Select d.Name as Department, e1.Name as Employee, e2.maxsal as Salary from Employee e1
Join (Select MAX(Salary) as maxsal, DepartmentId from Employee
Group BY DepartmentId) e2
ON e1.Salary = e2.maxsal AND e1.DepartmentId = e2.DepartmentId
Join Department d
ON e1.DepartmentId = d.Id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment