Write a SQL query to get the second highest salary from the Employee
table.html
+----+--------+ | Id | Salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+
For example, given the above Employee table, the second highest salary is 200
. If there is no second highest salary, then the query should return null
.函數
這道題讓咱們找表中某列第二大的數,這道題有不少種解法,先來看一種使用Limit和Offset兩個關鍵字的解法,MySQL中Limit後面的數字限制了咱們返回數據的個數,Offset是偏移量,那麼若是咱們想找第二高薪水,咱們首先能夠先對薪水進行降序排列,而後咱們將Offset設爲1,那麼就是從第二個開始,也就是第二高薪水,而後咱們將Limit設爲1,就是隻取出第二高薪水,若是將Limit設爲2,那麼就將第二高和第三高薪水都取出來:post
解法一:url
SELECT Salary FROM Employee GROUP BY Salary UNION ALL (SELECT NULL AS Salary) ORDER BY Salary DESC LIMIT 1 OFFSET 1;
咱們也能夠使用Max函數來作,這個返回最大值,邏輯是咱們取出的不包含最大值的數字中的最大值,即爲第二大值:spa
解法二:code
SELECT MAX(Salary) FROM Employee WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee);
下面這種方法和上面基本同樣,就是用小於號<代替了Not in關鍵字,效果相同:htm
解法三:blog
SELECT MAX(Salary) FROM Employee Where Salary < (SELECT MAX(Salary) FROM Employee);
最後來看一種能夠擴展到找到第N高的薪水的方法,只要將下面語句中的1改成N-1便可,第二高的薪水帶入N-1就是1,下面語句的邏輯是,假如咱們要找第二高的薪水,那麼咱們容許其中一個最大值存在,而後在其他的數字中找出最大的,即爲整個的第二大的值;leetcode
解法四:get
SELECT MAX(Salary) FROM Employee E1 WHERE 1 = (SELECT COUNT(DISTINCT(E2.Salary)) FROM Employee E2 WHERE E2.Salary > E1.Salary);
參考資料:
https://leetcode.com/discuss/47041/very-very-simple-solution
https://leetcode.com/discuss/42849/general-solution-not-using-max
https://leetcode.com/discuss/21751/simple-query-which-handles-the-null-situation