題目地址
https://leetcode-cn.com/problems/nth-highest-salary/
題目描述:第N高的薪水
編寫一個 SQL 查詢,獲取 Employee 表中第 n 高的薪水(Salary)。
示例:
+----+--------+ | Id | Salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+
例如上述 Employee 表,n = 2 時,應返回第二高的薪水 200。如果不存在第 n 高的薪水,那麼查詢應返回 null。
+---------------------+ | getNthHighestSalary(2) | +---------------------+ | 200 | +---------------------+
解答
這道題難就難在我不懂SQL語句。
學習點:1. 如何定義一個變量?
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
declare P INT;
set P = N-1;
RETURN (
# Write your MySQL query statement below.
select(
select distinct salary
from Employee
order by salary DESC
limit P,1
)
);
END