易妖游戏网
您的当前位置:首页SQL部门工资前三高的所有员工

SQL部门工资前三高的所有员工

来源:易妖游戏网

LeetCode原题

初始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 ');

需求:找出每个部门获得前三高工资的所有员工

首先

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
)

因篇幅问题不能全部显示,请点此查看更多更全内容