当前位置:   article > 正文

SQL部门工资前三高的所有员工_查询部门工资前三名sql

查询部门工资前三名sql

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');
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

在这里插入图片描述

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 ');
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

在这里插入图片描述

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

首先

思路:用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
  • 1
  • 2
  • 3
  • 4
  • 5

在这里插入图片描述

外层查询只需要连接一下部门得到名字

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
)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/615170
推荐阅读
相关标签
  

闽ICP备14008679号