[LeetCode] Nth Highest Salary 第N高薪水


 

Write a SQL query to get the nth highest salary from the Employee table.

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

For example, given the above Employee table, the nth highest salary where n = 2 is 200. If there is no nth highest salary, then the query should return null.

 

這道題是之前那道Second Highest Salary的拓展,根據之前那道題的做法,我們可以很容易的將其推展為N,根據對Second Highest Salary中解法一的分析,我們只需要將OFFSET后面的1改為N-1就行了,但是這樣MySQL會報錯,估計不支持運算,那么我們可以在前面加一個SET N = N - 1,將N先變成N-1再做也是一樣的:

 

解法一:

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  SET N = N - 1;
  RETURN (
      SELECT DISTINCT Salary FROM Employee GROUP BY Salary
      ORDER BY Salary DESC LIMIT 1 OFFSET N
  );
END

 

根據對Second Highest Salary中解法四的分析,我們只需要將其1改為N-1即可,這里卻支持N-1的計算,參見代碼如下:

 

解法二:

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  RETURN (
      SELECT MAX(Salary) FROM Employee E1
      WHERE N - 1 =
      (SELECT COUNT(DISTINCT(E2.Salary)) FROM Employee E2
      WHERE E2.Salary > E1.Salary)
  );
END

 

當然我們也可以通過將最后的>改為>=,這樣我們就可以將N-1換成N了:

 

解法三:

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  RETURN (
      SELECT MAX(Salary) FROM Employee E1
      WHERE N =
      (SELECT COUNT(DISTINCT(E2.Salary)) FROM Employee E2
      WHERE E2.Salary >= E1.Salary)
  );
END

 

類似題目:

Second Highest Salary

 

參考資料:

https://leetcode.com/discuss/88875/simple-answer-with-limit-and-offset

https://leetcode.com/discuss/63183/fastest-solution-without-using-order-declaring-variables

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

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



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