Employee
表有全部員工。每一個員工有 Id,salary 和 department Id 信息。算法
建立表和數據:spa
drop table Employee
Create table If Not Exists Employee (Idint, Name varchar(255), Salary int, DepartmentId int);
drop table Department Create table If Not Exists Department (Idint, Name varchar(255)); Truncate table Employee; insert into Employee (Id, Name, Salary,DepartmentId) values ('1', 'Joe', '70000', '1'); insert into Employee (Id, Name, Salary,DepartmentId) values ('2', 'Henry', '80000', '2'); insert into Employee (Id, Name, Salary,DepartmentId) values ('3', 'Sam', '60000', '2'); insert into Employee (Id, Name, Salary,DepartmentId) values ('4', 'Max', '90000', '1'); Truncate table Department; insert into Department (Id, Name) values('1', 'IT'); insert into Department (Id, Name) values('2', 'Sales');
解法:code
1.先找出每一個部門的最高薪水。blog
鏈接員工表和部門表,group by對部門分組,再求每組的最高薪水。用子查詢得出臨時表F(id,name,m)。table
( select D.id,D.name,max(E1.salary) as m from Department as D join Employee as E1 on (D.id = E1.departmentid) group by D.id,D.name ) as F
再次,鏈接員工表和臨時表F,條件是部門id相同且薪水與每一個部門最高薪水相同。與上面的組合起來得出算法:class
select F.name as Department,E.name as Employee,E.Salary from Employee as E join ( select D.id,D.name,max(E1.salary) as m from Department as D join Employee as E1 on (D.id = E1.departmentid) group by D.id,D.name ) as F on (E.departmentid = F.id and F.m = E.salary);
員工表中有部門id和薪水,但沒有部門name。可先求部門的最高薪水,造成臨時表,再鏈接員工表和部門表,取出部門name和員工name。則有下面的算法:select
select D.name as Department,E.name as Employee,E.Salary from Employee as E join ( select E1.departmentid,max(E1.salary) as m from Employee as E1 group by E1.departmentid ) as F on (E.departmentid = F.departmentid and F.m = E.salary) join Department as D on (F.departmentid = D.id)
2.對每個員工,找出員工所在部門的最高薪水。此處的查找過程,用子查詢實現。若是員工的薪水等於部門的最高薪水就是結果。im
select D.name as Department,E.name as Employee,E.Salary from Employee as E join Department as D on (E.departmentid = D.id) where E.salary = ( select max(E1.salary) from Employee as E1 where E1.departmentid = E.departmentid )
二元組(部門id,部門最高薪水)做爲總體t,結合in判斷t是否在已存在的組合中。數據
select D.name as Department,E.name as Employee,E.Salary from Employee as E join Department as D on (E.departmentid = D.id) where (E.departmentid,E.salary) in ( select E1.departmentid,max(E1.salary) from Employee as E1 where E1.departmentid group by E1.departmentid )