Mysql 第 n 高的薪水 相關知識整理

目錄

題目 

解題思路:

答案:

相關知識點:


 

 

 

 

題目 

 

編寫一個 SQL 查詢,獲取 Employee 表中第 n 高的薪水(Salary)。

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+


例如上述 Employee 表,n = 2 時,應返回第二高的薪水 200。如果不存在第 n 高的薪水,那麼查詢應返回 null。

+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200                    |

題目來源力扣(LeetCode)鏈接:https://leetcode-cn.com/problems/nth-highest-salary

 

解題思路:

  • 1、將薪水從大到小排序,第一個就是第一高,第二個就是第2高;使用order by Salary desc;
  • 2、薪水中可能重在重複值,所以使用distinct Salary;
  • 3、如何只顯示第n條數據,使用limit 1 offset n-1;
  • 4、考慮只有一條數據時,第二高爲空的情況,使用ifnull(exp,null);

例:求第3高;

select ifnull((select distinct Salary from Employee order by Salary desc limit 1 offset 2),null) 

 

答案:

該題定義函數getNthHighestSalary()

CREATE FUNCTION getNthHighestSalary(N INT)
 RETURNS INT
 BEGIN
 set N=N-1; 
 RETURN (  
     select ifnull((select distinct Salary from Employee order by Salary desc limit 1 offset N),null)
);
END

相關知識點:

  • distinct:去重複值
  • order by 字段名 asc/desc 正序或降序排列
  • limit n offset m: 跳過m條數據顯示n條數據;
    • 例子
      • limit 1 offset 2  跳過2條數據顯示1條數據  (1,2,3) 則顯示第3條數據
  • limit n,m 
    • limit 1,2  跳過第1條,再取4條數據
  • ifnull(exp,null)
    • 如果exp爲空,則爲null
  • mysql 自定義函數
    • create function functionName([parm type],[parm1 type],……)
          returns type
              begin語句;
              return 值;
              end;

       

 

 

 

 

 

 


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章