码迷,mamicode.com
首页 > 数据库 > 详细

找第二大的数SQL-Second Highest Salary

时间:2017-07-29 20:19:17      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:排序   distinct   class   end   from   ret   where   img   offset   

技术分享

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 INT
BEGIN
DECLARE 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 INT
BEGIN
DECLARE 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

标签:排序   distinct   class   end   from   ret   where   img   offset   

原文地址:http://www.cnblogs.com/fanhaha/p/7257178.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!