1. 程式人生 > >資料庫SQL實踐17:獲取當前薪水第二多的員工的emp_no以及其對應的薪水salary

資料庫SQL實踐17:獲取當前薪水第二多的員工的emp_no以及其對應的薪水salary

思想:

題目要求獲取當前(to_date='9999-01-01')薪水第二多的員工的emp_no以及其對應的薪水salary。首先通過條件to_date = '9999-01-01'獲取當前薪水,其次通過條件order by salary desc limit 1,1找到薪水第二多的員工(前提條件當前薪水沒有重複的)。

select emp_no,salary from salaries where to_date = '9999-01-01' order by salary desc limit 1,1;

下面是改進的程式。首先通過子查詢找到當前第二的薪水select distinct salary from salaries where to_date='9999-01-01' order by salary desc limit 1,1(通過distinct取沒有重複的當前薪水,然後按照降序排序,最後取出當前第二的薪水)。其次通過條件salary=子查詢找出當前第二工資的員工資訊。

select emp_no, salary from salaries
where to_date = '9999-01-01' and 
salary = (select distinct salary from salaries where to_date='9999-01-01' order by salary desc limit 1,1);