您的位置:首页 > 其它

[理解leetcode解法]176. Second Highest Salary

2016-03-02 15:58 405 查看

176. Second Highest Salary

#题目:

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
.

#题解:

方法一:

select MAX(Salary) from Employee
where Salary<(
    select MAX(Salary)
    from Employee
)

方法二:

select case
when count(Salary) >=1 then(
    select distinct Salary
    from Employee
    order by Salary desc
    limit 1,1)
else null
end as NthSalary
from Employee

#题释:

严谨写法:

SELECT IFNULL( (SELECTdistinct Salary as SecondHighestSalary FROM Employee orderby Salary desc limit 1,1)
,null);


SQL之limit用法

mysql支持limit

select * from tablename limit 0,1

即取出第一条记录。

select * from tablename limit 1,1

第二条记录

select * from tablename limit 10,20

从第11条到31条(共计20条)

注意mysql语法的IFNULL关键字的用法:

MYSQL IFNULL(expr1,expr2) 如果expr1不是NULL,IFNULL()返回expr1,否则它返回expr2。IFNULL()返回一个数字或字符串值,取决于它被使用的上下文环境。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode