Leetcode177题 https://leetcode-cn.com/problems/nth-highest-salary/
编写一个 SQL 查询,获取 Employee 表中第 n 高的薪水(Salary)。
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
例如上述 Employee
表,n = 2 时,应返回第二高的薪水 200
。如果不存在第 n 高的薪水,那么查询应返回 null
。
+-------------------------------+
| getNthHighestSalary(2) |
+-------------------------------+
| 200 |
+-------------------------------+
我们可以使用limit、offset
当 limit和offset组合使用的时候,limit后面的参数表示要取的字段数据量,offset表示要跳过的数据量 ,本题要求取第N高的数据,即一条数据,limit后面自然跟1,offset则为前n-1条的数据(跳过),数据降序排列desc
我们在函数里面定义一个变量m=n-1
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
declare m int;
set m= n-1;
RETURN (
select distinct e.Salary
from Employee e
group by e.Salary
order by e.Salary desc limit 1 offset m
);
END