编写一个 SQL 查询,获取 Employee 表中第 n 高的薪水(Salary)。
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
例如上述 Employee 表,n = 2 时,应返回第二高的薪水 200。如果不存在第 n 高的薪水,那么查询应返回 null。
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200 |
+------------------------+
题目分析:
第n高 需要创建一个函数,要求如果存在返回,不存在返回null 需要使用IF()
答案:
create funtion getNthHighestSalary(N int) returns int
begin
set N=N;
return (
select (IF((select count(*) from (select distinct e.Salary from employee e)
e) >= N, select min(e.Salary) from (select distinct e.Salary from order by e.Salary desc limit N) e) , NULL))
);
end