zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Leetcode No.177 第N高的薪水

2023-03-20 14:56:39 时间

一、题目描述

编写一个 SQL 查询,获取 Employee 表中第 n 高的薪水(Salary)。

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

例如上述 Employee 表,n = 2 时,应返回第二高的薪水 200。如果不存在第 n 高的薪水,那么查询应返回 null。

+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200                    |
+------------------------+

二、解题思路

使用DENSE_RANK连续排名函数

SQL四大排名函数(ROW_NUMBER、RANK、DENSE_RANK、NTILE)

https://xingqijiang.blog.csdn.net/article/details/120110950

三、代码

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  RETURN (
      # Write your MySQL query statement below.
      select distinct(salary)
      from(
            select salary,dense_rank()over(order by Salary desc) as rn
            from Employee
      )a 
      where a.rn=N
  );
END