LeetCode#第N高的薪水

201 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第6天,点击查看活动详情

一、题目

表: Employee

+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| salary      | int  |
+-------------+------+

Id是该表的主键列。 该表的每一行都包含有关员工工资的信息。  

编写一个SQL查询来报告 Employee 表中第 n 高的工资。如果没有第 n 个最高工资,查询应该报告为 null 。

查询结果格式如下所示。

 

示例 1:

输入: 
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+
n = 2
输出: 
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200                    |
+------------------------+
示例 2:

输入: 
Employee 表:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
+----+--------+
n = 2
输出: 
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| null                   |
+------------------------+
  • 来源:力扣(LeetCode)
  • 链接:leetcode.cn/problems/nt…
  • 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、解题

创建数据表

根据题意创建数据表

create table if not exists Employee (
    Id int,
    Salary int
);
truncate table Employee;
insert into Employee values (1, 100),
                            (2, 200),
                            (3, 300);

解题

  • 首先根据题意要求第n高的工资,最好的求的方式先对薪水进行排序
  • 得到按降序排列的数据后,可以使用limit,根据偏移量进行查找
  • 这是就可以得到想要的任何一个排序的薪资,但是偏移量需要处理,比如n=2输出第二个,那么输入的值需要-1,才能得到想要的偏移量
  • 根据题意如果没有则返回null,这里可以使用ifnull判断如有则返回数据,没有则返回null
  • 根据题意创建函数,执行函数得到结果

代码

create function getNthHighestSalary(N int) returns int
begin
    declare m int;
    set m=n-1;
    return (select ifnull((select distinct Salary from Employee order by Salary desc limit m,1),null)
        );

end;

三、执行结果

image.png

四、总结

  • limit A B: limit可以接收一个或者两个数字参数,参数必须是常量,第一个参数是偏移量(从第A个开始),第二个参数返回记录行的数据条数。
  • ifnull(exp, null):ifnull第一个参数是表达式,第二个是默认值,如果表达式为真则返回表达式的数据,否则返回第二个参数
  • 函数function
create function 函数名([参数列表]) returns 参数类型
begin
    sql语句
    return 返回值;
end