編寫一個 SQL 查詢,獲取 Employee 表中第 n 高的薪水(Salary)。
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
例如上述 Employee 表,n = 2 時,應返回第二高的薪水 200。如果不存在第 n 高的薪水,那麼查詢應返回 null。
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200 |
+------------------------+
https://leetcode.com/problems/second-highest-salary/
LIMIT 後面可以有兩個參數,而且必須是整數,第一個:開始的偏移量(從0開始算),第二個:返回行的最大數目。
比如:limit N,1表示從第N個數開始(從0計算),取1個。
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
SET N = N - 1;
RETURN (
select distinct salary
from Employee
order by salary desc
limit N,1
);
END