国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > 数据库 > 数据库应用 > Second Highest Salary

Second Highest Salary

来源:程序员人生   发布时间:2015-05-27 07:48:44 阅读次数:2577次
    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 second highest salary is 200. If there is no second highest salary, then the query should return null.
解法1:
    # Write your MySQL query statement below
    select(select salary from Employee group by salary order by salary desc limit 1,1) as 'SecondHighestSalary';
解法2:
    select max(salary)
        from Employee
            where salary < (select max(salary) from Employee)
要点:
    1、去重,所以使用group by进行分组

    2、由于要得到第2大工资,所以需要进行排序,

    3、max得到的最大值,但是要得到第2个最大值,所以要使用limit 1,1

    limit start,len

    start 表示页数,0,1,2,3....

    len表示页的记录数

    4、由于答案的列名是SecondHighestSalary,所以最后要使用as 重命名

    5、需要使用两个select,第2个select用于重建列和列值。由于second highest salary 如果不存在的话,那末内部的select返回值是null,不符合答案。因此需要对内部select进行重建列和列值。
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生