1. 程式人生 > >資料庫SQL實踐23: 對所有員工的薪水按照salary進行按照1-N的排名

資料庫SQL實踐23: 對所有員工的薪水按照salary進行按照1-N的排名

思想:

題目要求對所有員工的當前(to_date='9999-01-01')薪水按照salary進行按照1-N的排名,相同salary並列且按照emp_no升序排列。

首先通過條件where s1.to_date='9999-01-01' and s2.to_date='9999-01-01' and s1.salary <= s2.salary 找出員工當前的工資並找出等於和高於它的工資。

其次通過條件group by s1.emp_no實現按照emp_no分組,並計算distinct s2.salary的個數即它的排名

最後通過條件order by s1.salary desc,s1.emp_no asc對結果集按照s1.salary降序排,若s1.salary一樣就按emp_no升序排

select s1.emp_no,s1.salary,count(distinct s2.salary) as rank from salaries s1,salaries s2 
where s1.to_date='9999-01-01' and s2.to_date='9999-01-01' and s1.salary <= s2.salary 
group by s1.emp_no order by s1.salary desc,s1.emp_no asc;