1. 程式人生 > 實用技巧 >SQL 分組內取前幾名的問題

SQL 分組內取前幾名的問題

查詢 部門工資前三高的所有員工

比如這題,找每個部門的工資前三名,那麼先在子查詢中用Employee和自己做連線,
連線條件是【部門相同但是工資比我高】,那麼接下來按照having count(Salary) <= 2
來篩選的原理是:如果【跟我一個部門而且工資比我高的人數】不超過2個,那麼我一定是部門工資前三,
這樣內層查詢可以查詢出所有符合要求的員工ID,接下來外層查詢就簡單了。```
![](https://img2020.cnblogs.com/blog/1044397/202008/1044397-20200819105206232-299161010.png)

select d.Name as Department,e.Name as Employee,e.Salary as Salary
from Employee as e left join Department as d
on e.DepartmentId = d.Id
where e.Id in
(
select e1.Id
from Employee as e1 left join Employee as e2
on e1.DepartmentId = e2.DepartmentId and e1.Salary < e2.Salary
group by e1.Id
having count(distinct e2.Salary) <= 2
)
and e.DepartmentId in (select Id from Department)
order by d.Id asc,e.Salary desc