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

在这里插入图片描述

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
)

在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值