SQL 分組內取前幾名的問題


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

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

# 內層查詢,找前三高工資員工
select e1.Id
from Employee e1 left join Employee e2
# 和我(e1)在同一部門的
on e1.DepartmentId=e2.DepartmentId
# 且工資比我高的
and e1.Salary<e2.Salary
# 不超過2個
group by Id
having count(distinct e2.Salary)<=2
# 外層查詢
select d.Name as Department,e.Name as Employee,e.Salary as Salary
from Employee e left join Department d
on  e.DepartmentId=d.Id
where e.Id in (
    "內層Id 結果集"
    )
    and e.DepartmentId in(
        select Id
        from Department
    )
order by d.Id asc,e.Salary desc
# 外層查詢
select d.Name as Department,e.Name as Employee,e.Salary as Salary
from Employee e left join Department d
on  e.DepartmentId=d.Id

where e.Id in (
    # 內層查詢,找前三高工資員工
select e1.Id
from Employee e1 left join Employee e2
# 和我(e1)在同一部門的
on e1.DepartmentId=e2.DepartmentId
# 且工資比我高的
and e1.Salary<e2.Salary
# 不超過2個
group by Id
having count(distinct e2.Salary)<=2
    )
    and e.DepartmentId in(
        select Id
        from Department
    )
order by d.Id asc,e.Salary desc


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM