标签:控制语句,limit,子查询
2022年12月2日
题目:
编写一个SQL查询来报告 Employee
表中第 n
高的工资。如果没有第 n
个最高工资,查询应该报告为 null
。
Employee表
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| salary | int |
+-------------+------+
Id是该表的主键列。
该表的每一行都包含有关员工工资的信息。
1.方法一
limit用法
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
SET N = N-1;
RETURN (
# Write your MySQL query statement below.
select
ifnull(
(select distinct salary
from Employee
order by salary desc
limit N,1),
null
)
);
END
2.方法二
子查询
- 排名第N的薪水意味着该表中存在N-1个比其更高的薪水
- 注意这里的N-1个更高的薪水是指去重后的N-1个,实际对应人数可能不止N-1个最后返回的薪水也应该去重,因为可能不止一个薪水排名第N
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
RETURN (
# Write your MySQL query statement below.
select
distinct e.salary
from
employee e
where
(select count(distinct salary) from employee where salary>e.salary) = N-1
);
END