题目描述
编写一个SQL
查询,获取Employee
表中的第n高的薪水(Salary)。
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
例如上述的Employee
表中,n=2时,应该返回第二高的薪水200
。
如果不存在第n高的薪水,那么就返回null
。
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200 |
+------------------------+
算法设计与分析:
方法一:使用子查询和LIMIT
子句
- 算法:传入的参数是N,将不同的薪资按照降序进行排序,然后使用
LIMIT
子句获得第n高的薪资,注意limit n,m
的用法:limit 2,3:返回的是3,4,5位置的数据,即范围是(n+1,n+m)。
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
set n = N-1;
RETURN (
# Write your MySQL query statement below.
select distinct
Salary
from
Employee
order by
Salary
# 返回的是第N条数据,前面已经设置n=N-1,所以这里直接返回第n+1条这一条数据。
desc limit n, 1
);
END
方法二:使用IFNULL
和LIMIT
子句
解决“NULL”问题的另外一种方法是使用“IFNULL”函数,其值差不多:
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
declare P int default N-1;
if (P<0) then
return null;
else
return (
# Write your MySQL query statement below.
select IFNULL((
select distinct
Salary
from
Employee
order by
Salary
desc limit P, 1
),null) as getNthHighestSalary
);
end if;
END
一些技巧性的东西要积累:
- 和176道题目差不多,这里使用活值!
- distinct :去除重复的值,因为返回的值可能会包含重复的值,本题如果不加,就通不过他那个设置重复值的测试用例。
- IFNULL(xxx,null) :返回空值处理
- AS xxx :取别名
- limit n,m:获取n+1到之后的m条数据
- order by xxx desc: 按照字段xxx降序排序
注: 本题解参考到leetcode官方题解。