码迷,mamicode.com
首页 > 其他好文 > 详细

LeeCode——Second Highest Salary

时间:2019-10-07 23:45:02      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:order by   null   个数   set   复数   table   from   mysql   tin   

Write a SQL query to get the second highest salary from the Employee table.

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

For example, given the above Employee table, the query should return 200 as the second highest salary.  
If there is no second highest salary, then the query should return null.

+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

此题的难点是:

  • 针对可能存在的重复数值,选出唯一的数值(使用distinct);
  • 选取第二个数值,则需要使用limit,offset确定数值;
  • 查询的数值可能为不存在,此时就需要返回NULL(使用IFNULL).

答题如下所示:

# Write your MySQL query statement below
select 
    ifnull(
        (select distinct Salary from Employee order by Salary desc limit 1,1),
        NULL
    )
    as SecondHighestSalary

LeeCode——Second Highest Salary

标签:order by   null   个数   set   复数   table   from   mysql   tin   

原文地址:https://www.cnblogs.com/jason1990/p/11632706.html

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