首页 > 代码库 > 找第二大的数SQL-Second Highest Salary

找第二大的数SQL-Second Highest Salary

技术分享

1: 找小于最大的最大的

select max(Salary) from Employee where Salary<(select MAX(Salary) from Employee);

2. 排序

select  Salary from Employee where Salary not in (select MAX(Salary)from Employee) order by Salary desc limit 1;

  

select (select distinct Salary from Employee order by Salary Desc limit 1 offset 1) as SecondHeighestSalary;

  

 

找第n个数:

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INTBEGINDECLARE M INT;set N=N-1;  RETURN (           # Write your MySQL query statement below.      select  Salary from Employee order by Salary desc limit 1 offset N  );END

  

技术分享

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INTBEGINDECLARE M INT;set N=N-1;  RETURN (           # Write your MySQL query statement below.      select  distinct Salary from Employee order by Salary desc limit 1 offset N  );END

  不能在limit 里N-1, 因为limit里不计算

哈哈: distinct :在表中可能包含重复值,返回唯一不同的值,

找第二大的数SQL-Second Highest Salary