zoukankan      html  css  js  c++  java
  • LeetCode176——第二高的薪水

    题目描述

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

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

    例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null

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

    思路

    1. 排序,取出排名第二的值
    select Salary from Employee
      order by Salary desc
      limit 1, 1;
    
    1. group by 过滤掉相同薪水
    select Salary from Employee
      group by Salary
      order by Salary desc
      limit 1, 1;
    
    1. 当不存在第二高的薪水时,会返回空而不是 null,做个是否为 null 的判断
    select
      ifnull(
        (select Salary from Employee group by Salary order by Salary desc limit 1, 1),
        null
      ) as SecondHighestSalary;
    

    可以简写为

    select 
      (select Salary from Employee group by Salary order by Salary desc limit 1, 1)
      as SecondHighestSalary;
    
  • 相关阅读:
    CODE[VS] 2506 可恶的体育老师
    CODE[VS] 3411 洪水
    CODE[VS] 2692 小明过生日
    CODE[VS] 2291 糖果堆
    CODE[VS] 2008 你已经爱我多久了
    忽然之间
    Amazing grace 奇异恩典
    无处安放
    AC日记
    AC日记
  • 原文地址:https://www.cnblogs.com/chaohangz/p/11050405.html
Copyright © 2011-2022 走看看