美文网首页
LeetCode数据库—第二高的薪水

LeetCode数据库—第二高的薪水

作者: Taodede | 来源:发表于2018-11-07 17:09 被阅读20次

    SQL架构:

    Create table If Not Exists Employee (Id int, Salary int);
    Truncate table Employee;
    insert into Employee (Id, Salary) values ('1', '100');
    insert into Employee (Id, Salary) values ('2', '200');
    insert into Employee (Id, Salary) values ('3', '300');
    

    查看所有记录:

    mysql> select * from Employee;
    +------+------+--------+--------------+
    | Id   | Name | Salary | DepartmentId |
    +------+------+--------+--------------+
    |    1 | NULL |    100 |         NULL |
    |    2 | NULL |    200 |         NULL |
    |    3 | NULL |    300 |         NULL |
    +------+------+--------+--------------+
    3 rows in set (0.00 sec)
    

    编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary)。
    例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。

    +-----------------------------+
    | SecondHighestSalary |
    +-----------------------------+
    | 200 |
    +-----------------------------+
    查询:
    方法一:

    mysql> select ifnull(salary,NULL) as SecondHighestSalary from
        -> (select * from employee order by salary desc)e
        -> limit 1 offset 1;
    +---------------------+
    | SecondHighestSalary |
    +---------------------+
    |                 200 |
    +---------------------+
    1 row in set (0.00 sec)
    

    方法二:

    mysql> select ifnull(Salary,NULL) as SecondHighestSalary from
        -> Employee e1
        -> where (select count(distinct salary) from Employee e2 where e2.salary>e1.salary)=1;
    +---------------------+
    | SecondHighestSalary |
    +---------------------+
    |                 200 |
    +---------------------+
    1 row in set (0.00 sec)
    

    相关文章

      网友评论

          本文标题:LeetCode数据库—第二高的薪水

          本文链接:https://www.haomeiwen.com/subject/ixivxqtx.html