★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-kszfojvm-md.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Write a SQL query to get the second highest salary from the Employee
table.mysql
+----+--------+ | Id | Salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+
For example, given the above Employee table, the query should return 200
as the second highest salary. If there is no second highest salary, then the query should return null
.git
+---------------------+ | SecondHighestSalary | +---------------------+ | 200 | +---------------------+
編寫一個 SQL 查詢,獲取 Employee
表中第二高的薪水(Salary) 。github
+----+--------+ | Id | Salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+
例如上述 Employee
表,SQL查詢應該返回 200
做爲第二高的薪水。若是不存在第二高的薪水,那麼查詢應返回 null
。算法
+---------------------+ | SecondHighestSalary | +---------------------+ | 200 | +---------------------+
LIMIT
子句算法:按降序對不一樣的工資進行排序,而後利用該LIMIT
子句得到第二高的工資。sql
1 SELECT DISTINCT 2 Salary AS SecondHighestSalary 3 FROM 4 Employee 5 ORDER BY Salary DESC 6 LIMIT 1 OFFSET 1
可是,若是沒有這樣的第二高薪,這個解決方案將被斷定爲「錯誤答案」,由於此表中可能只有一條記錄。爲了解決這個問題,咱們能夠將其做爲臨時表。微信
1 SELECT 2 (SELECT DISTINCT 3 Salary 4 FROM 5 Employee 6 ORDER BY Salary DESC 7 LIMIT 1 OFFSET 1) AS SecondHighestSalary 8 ;
IFNULL
和LIMIT
子句解決'NULL'問題的另外一種方法是使用IFNULL
以下功能。app
1 SELECT 2 IFNULL( 3 (SELECT DISTINCT Salary 4 FROM Employee 5 ORDER BY Salary DESC 6 LIMIT 1 OFFSET 1), 7 NULL) AS SecondHighestSalary
105msspa
1 # Write your MySQL query statement below 2 select ( 3 select distinct Salary from Employee order by Salary Desc limit 1 offset 1 4 )as SecondHighestSalary
106mscode
1 # Write your MySQL query statement below 2 select max(salary) as SecondHighestSalary 3 from employee 4 where salary < (select max(salary) from employee)
108ms
1 # Write your MySQL query statement below 2 # select distinct Salary SecondHighestSalary from Employee order by Salary DESC limit 1,1 3 select ifNull((select distinct Salary from Employee order by Salary Desc limit 1,1),null) as SecondHighestSalary
110ms
1 # Write your MySQL query statement below 2 SELECT IFNULL( (SELECT DISTINCT salary 3 FROM Employee 4 ORDER BY salary DESC 5 LIMIT 1,1),NULL) AS SecondHighestSalary;