Mysql-- 查询结果集中排序第N高的记录

Posted Hepburn Yang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mysql-- 查询结果集中排序第N高的记录相关的知识,希望对你有一定的参考价值。

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

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

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

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

实现思路:利用limit分页思想+order by排序:

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
 -- 不考虑n<1的情况
 # declare p int;
 # set p =N-1;

-- 考虑n<1的情况
    declare p1 int;
    declare p2 int;
 if (N<1) 
 then set p1 =0,p2 =0;
 else set p1 =N-1, p2=1;
 end if;
 
  RETURN (
      # Write your mysql query statement below.
      select IfNULL(
      ( select Distinct Salary from Employee Order by Salary Desc limit p1 , p2),null)
      as SecondHighestSalary
  );
END

以上是关于Mysql-- 查询结果集中排序第N高的记录的主要内容,如果未能解决你的问题,请参考以下文章