Buckle 176. second highest salary

Buckle 176. second highest salary

https://leetcode-cn.com/problems/second-highest-salary/

Write a SQL query to get the second highest salary (Salary) in the Employee table.

+ ---- + -------- +
| Id | Salary |
+ ---- + -------- +
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+ ---- + -------- +
For example in the Employee table above, the SQL query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.

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

Method 1:

# Write your MySQL query statement below
select 
(select distinct Salary  #distinct 返回唯一不同的值
from Employee 
order by Salary desc#降序排列
limit 1,1)#第二高   
#limit x,y ,是跳过x行,取y行数据的意思,类似于 limit y offset x, 而不是类似于 limit x offset y。 limit x offset y是跳过y行,取x行数据
as SecondHighestSalary;#看成一张临时表

Method 2:

ifnull statement

select 
(
    ifnull
    (
        (select distinct salary #distinct 返回唯一不同的值
        from employee 
        order by salary desc #降序排列
        limit 1,1)
    ,null)
    #limit x,y ,是跳过x行,取y行数据的意思,类似于 limit y offset x, 而不是类似于 limit x offset y。 limit x offset y是跳过y行,取x行数据
)
as SecondHighestSalary;#看成一张临时表

 

Published 23 original articles · praised 0 · visits 137

Guess you like

Origin blog.csdn.net/qq_35683407/article/details/105424698