SQL 分组内求最大N个或最小N个
阅读原文时间:2023年07月09日阅读:1

题目描述

表 Employee

+----+-------+--------+--------------+
| Id | Name | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1 | Joe | 70000 | 1 |
| 2 | Henry | 80000 | 2 |
| 3 | Sam | 60000 | 2 |
| 4 | Max | 90000 | 1 |
| 5 | Janet | 69000 | 1 |
| 6 | Randy | 85000 | 1 |
+----+-------+--------+--------------+

表 Department

+----+----------+
| Id | Name |
+----+----------+
| 1 | IT |
| 2 | Sales |
+----+----------+

要求每个部门员工中挣得所在部门前三的工资,由于有多人可能工资一样,故每个部门求出的人数可能大于3
结果如下:

+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT | Max | 90000 |
| IT | Randy | 85000 |
| IT | Joe | 70000 |
| Sales | Henry | 80000 |
| Sales | Sam | 60000 |
+------------+----------+--------+

SQL语句

select a.Name as Department,b.Name as Employee,b.Salary from
Department a
join
(select * from Employee e1 where (select
count(distinct Salary) from Employee e2 where e2.Salary>e1.Salary
and e1.DepartmentId=e2.DepartmentId)<3) b
on b.DepartmentId=a.Id
order by a.Id,b.Salary desc;

#查出每个部门中工资是前三水平的员工
select * from Employee e1
where
(select count(distinct Salary) from Employee e2 where e2.Salary>e1.Salary and e1.DepartmentId=e2.DepartmentId)
<3

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器