LeetCode_sql_day33(177.第N高的薪水)

描述   177.第N高的薪水

表: Employee

+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| salary      | int  |
+-------------+------+
在 SQL 中,id 是该表的主键。
该表的每一行都包含有关员工工资的信息。

查询 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                   |
+------------------------+

数据准备

Create table If Not Exists Employee (Id int, Salary int)
Truncate table Employee
insert into Employee (id, salary) values ('1', '100')
insert into Employee (id, salary) values ('2', '200')
insert into Employee (id, salary) values ('3', '300')

分析

法一  可以使用limit 取第N个 

limit 2,1  就是 第三高  那么 limit n-1,1 就是第N个

法二  用窗口函数给工资排名  取第N个

代码

法一:

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
        declare n int;
        set n = N-1;

  RETURN (

      select salary from employee order by salary desc limit n,1);


END

法二:


CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN

    RETURN (with t1 as (select salary,
                               dense_rank() over (order by salary desc) r1
                        from employee)
            select distinct salary
            from t1
            where r1 = N);


END;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值