176. 第二高的薪水

mac2023-06-09  16

题目链接:https://leetcode.com/problems/second-highest-salary/

编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。

+----+--------+ | Id | Salary | +----+--------+ | 1  | 100    | | 2  | 200    | | 3  | 300    | +----+--------+ 例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。

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

 

思路:

用distinct去重,然后用limit取出特定大小的那一个元素,注意元素不存在的情况。

select (

            select DISTINCT

             salary

              from  Employee                order by salary desc limit 1,1)

             as SecondHighestSalary

 

方法二:

用ifnull函数:

SELECT     IFNULL(       (SELECT DISTINCT        Salary        FROM Employee        ORDER BY Salary DESC         LIMIT 1 , 1),     NULL) AS SecondHighestSalary

最新回复(0)