【Leetcode数据库177】获取 Employee 表中第 n 高的薪水(Salary)

编写一个 SQL 查询,获取 Employee 表中第 n 高的薪水(Salary)。
+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+
例如上述 Employee 表,n = 2 时,应返回第二高的薪水 200。如果不存在第 n 高的薪水,那么查询应返回 null。
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200                    |
+------------------------+

解决:
一、Mysql

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
declare m INT;
set m = n-1;
  RETURN (
      # Write your MySQL query statement below.
      SELECT distinct Salary FROM Employee order by salary desc limit m,1
  );
END

Limit的索引从0开始


二、Oracle

CREATE FUNCTION getNthHighestSalary(N IN NUMBER) RETURN NUMBER IS
result NUMBER;
BEGIN
    /* Write your PL/SQL query statement below */
    select salary into result
      from (
          select salary,rank() over(order by salary desc) as rn from employee
      )a
     where rn = n;
    RETURN result;
END;

注意select需要into返回的参数。

猜你喜欢

转载自blog.csdn.net/debimeng/article/details/104457029