题目描述:
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.
题目大意:
编写一个SQL查询获取雇员表中的第二高的薪水值。
例如,上表中的第二高薪水为200.如果没有第二高薪水,查询应该返回null。
解题思路:
题目中所谓的“第二高”是指去重后的仅次于最高值的分数。
因此只需借助于MAX关键词即可完成题目。
SQL语句:
SELECT MAX(Salary)
FROM Employee
WHERE Salary < (SELECT MAX(Salary) FROM Employee);
如果不去重,SQL语句可以这么写:
SELECT (SELECT Salary AS SecondHighestSalary FROM Employee ORDER BY Salary DESC LIMIT 1,1);
嵌套的SELECT可以取代IFNULL函数。
参阅LeetCode Discuss:https://oj.leetcode.com/discuss/21202/my-answer-about-this-question-using-ifnull-and-distinct
本文链接:http://bookshadow.com/weblog/2015/01/12/leetcode-second-highest-salary/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。