LeetCode原题
https://leetcode-cn.com/problems/department-top-three-salaries/
初始sql
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`id` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`salary` decimal(10,2) DEFAULT NULL,
`deptId` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `employee` VALUES ('1', 'Joe', '85000.00', '1');
INSERT INTO `employee` VALUES ('2', 'Henry', '80000.00', '2');
INSERT INTO `employee` VALUES ('3', 'Sam', '60000.00', '2');
INSERT INTO `employee` VALUES ('4', 'Max', '90000.00', '1');
INSERT INTO `employee` VALUES ('5', 'Janet', '69000.00', '1');
INSERT INTO `employee` VALUES ('6', 'Randy', '85000.00', '1');
INSERT INTO `employee` VALUES ('7', 'Will', '70000.00', '1');
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`id` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `department` VALUES ('1', 'IT');
INSERT INTO `department` VALUES ('2', 'Sales ');
需求:找出每个部门获得前三高工资的所有员工
首先
思路:用Employee和自己做连接,连接条件是部门相同但是工资比我高,那么接下来按照having count(Salary) <= 2来筛选,原理是跟我一个部门而且工资比我高的人数不超过2个,那么我一定是部门工资前三,并求出这些员工id
select e1.Id
from Employee as e1 left join Employee as e2
on e1.DeptId = e2.DeptId and e1.Salary < e2.Salary
group by e1.Id
having count(distinct e2.Salary) <= 2
外层查询只需要连接一下部门得到名字
select d.Name as Department,e.Name as Employee,e.Salary as Salary
from Employee as e left join Department as d
on e.DeptId = d.Id
where e.Id in
(
select e1.Id
from Employee as e1 left join Employee as e2
on e1.DeptId = e2.DeptId and e1.Salary < e2.Salary
group by e1.Id
having count(distinct e2.Salary) <= 2
)