[LeetCode] 177.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的拓展,根據(jù)之前那道題的做法,我們可以很容易的將其推展為N,根據(jù)對(duì)Second Highest Salary中解法一的分析,我們只需要將OFFSET后面的1改為N-1就行了,但是這樣MySQL會(huì)報(bào)錯(cuò),估計(jì)不支持運(yùn)算,那么我們可以在前面加一個(gè)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
根據(jù)對(duì)Second Highest Salary中解法四的分析,我們只需要將其1改為N-1即可,這里卻支持N-1的計(jì)算,參見(jiàn)代碼如下:
解法二:
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
當(dāng)然我們也可以通過(guò)將最后的>改為>=,這樣我們就可以將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
類(lèi)似題目:
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
到此這篇關(guān)于SQL實(shí)現(xiàn)LeetCode(177.第N高薪水)的文章就介紹到這了,更多相關(guān)SQL實(shí)現(xiàn)第N高薪水內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- SQL實(shí)現(xiàn)LeetCode(184.系里最高薪水)
- SQL實(shí)現(xiàn)LeetCode(183.從未下單訂購(gòu)的顧客)
- SQL實(shí)現(xiàn)LeetCode(182.重復(fù)的郵箱)
- SQL實(shí)現(xiàn)LeetCode(181.員工掙得比經(jīng)理多)
- SQL實(shí)現(xiàn)LeetCode(180.連續(xù)的數(shù)字)
- SQL實(shí)現(xiàn)LeetCode(178.分?jǐn)?shù)排行)
- SQL實(shí)現(xiàn)LeetCode(176.第二高薪水)
- SQL實(shí)現(xiàn)LeetCode(185.系里前三高薪水)