Write a SQL query to get the nth highest salary from the Employee
table.html
+----+--------+ | 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
.post
這道題是以前那道Second Highest Salary的拓展,根據以前那道題的作法,咱們能夠很容易的將其推展爲N,根據對Second Highest Salary中解法一的分析,咱們只須要將OFFSET後面的1改成N-1就好了,可是這樣MySQL會報錯,估計不支持運算,那麼咱們能夠在前面加一個SET N = N - 1,將N先變成N-1再作也是同樣的:url
解法一:spa
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的計算,參見代碼以下:code
解法二:htm
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了:blog
解法三:leetcode
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
相似題目:get
參考資料:
https://leetcode.com/discuss/88875/simple-answer-with-limit-and-offset
https://leetcode.com/discuss/63183/fastest-solution-without-using-order-declaring-variables