[理解leetcode解法]176. Second Highest Salary
阿新 • • 發佈:2019-02-01
176. Second Highest Salary
#題目:
Write a SQL query to get the second highest salary from theEmployee
table.
+----+--------+ | Id | Salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+
For example, given the above Employee table, the second highest salary is200
.
If there is no second highest salary, then the query should returnnull
#題解:
方法一: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支援limitselect * 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()返回一個數字或字串值,取決於它被使用的上下文環境。 |