The Employee
table holds all employees. Every employee has an ID, a salary, and there are also a column for the department ID.
+----+-------+--------+--------------+| Id | Name | Salary | DepartmentID |+----+-------+--------+--------------+| 1 | Joe | 70000 | 1 | | 2 | Henry | 80000 | 2 | | 3 | Sam | 60000 | 2 | | 4 | Max | 90000 | 1 |+----+-------+--------+--------------+
The Department
table holds all departments of the company.
+----+----------+| Id | Name |+----+----------+| 1 | IT | | 2 | Sales |+----+----------+
Write a SQL query to find employees who has the highest salary in each of the departments. For the above tables, Max have the highest salary in the IT department and Henry have the highest salary in the Sales depart ment.
+------------+----------+--------+| Department | Employee | Salary |+------------+----------+--------+| IT | Max | 90000 | | Sales | Henry | 80000 |+------------+----------+--------+
Requirements: Find the highest-paid employees in each department
CREATE TABLE Employee (
Id TINYINT UNSIGNED,
Name VARCHAR (20),
Salary DECIMAL (10,2),
DepartmentID TINYINT
) Engine=myisam Charset=utf8;
CREATE TABLE Department (
Id TINYINT UNSIGNED,
Name VARCHAR (20)
) Engine=myisam Charset=utf8;
SELECT b.nm,a.name,a.salary
From Employee a INNER JOIN (
SELECT T2. Id,t2. Name Nm,max (t1.salary) Sal
From employee T1 INNER joins department T2 on T1. Departmentid=t2. Id
GROUP by T1. DepartmentID
) b on A.salary=b.sal and a.departmentid=b.id
[Leetcode]-database-department Highest Salary