Second Highest Salary Leetcode
2015-05-06 14:12
267 查看
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.
找到第二大的工资值。
找第几大的,最简单的思路就是通过ORDER BY 和 LIMIT组合进行查找。
所以开始答案是这样的:
但是这个解法不能满足如果没有值的话返回null这个要求,所以要加上判断语句,即:
但是,因为这道题目要求的是寻找的2大的值,而不是第n大的值,所以也可以使用max来完成,并且max()函数如果找不到合适的值就会返回null,所以比较简单。具体SQL语句如下:
+—-+——–+
| 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.
找到第二大的工资值。
找第几大的,最简单的思路就是通过ORDER BY 和 LIMIT组合进行查找。
所以开始答案是这样的:
SELECT distinct Salary FROM Employee Order by Salary desc Limit 1,1
但是这个解法不能满足如果没有值的话返回null这个要求,所以要加上判断语句,即:
SELECT IFNULL((SELECT distinct Salary FROM Employee Order by Salary desc Limit 1,1),NULL);
但是,因为这道题目要求的是寻找的2大的值,而不是第n大的值,所以也可以使用max来完成,并且max()函数如果找不到合适的值就会返回null,所以比较简单。具体SQL语句如下:
SELECT MAX(SALARY) FROM EMPLOYEE WHERE SALARY<(SELECT MAX(SALARY) FROM EMPLOYEE);
相关文章推荐
- leetcode176---Second Highest Salary
- 【leetcode】database Second Highest Salary
- Leetcode 176 Second Highest Salary
- LeetCode - Second Highest Salary
- leetcode 176. Second Highest Salary
- Leetcode176. Second Highest Salary
- leetcode-Second Highest Salary
- [leetcode]175 Second Highest Salary
- leetcode 176. Second Highest Salary
- leetcode 2--Second Highest Salary
- LeetCode-Algorithms #002 Add Two Numbers, Database #176 Second Highest Salary
- leetcode-Second Highest Salary
- Database LeetCode Second Highest Salary
- leetcode 176. Second Highest Salary
- LeetCode 176. Second Highest Salary
- LeetCode Database #176 Second Highest Salary
- Leetcode: Second Highest Salary
- 【LeetCode】Second Highest Salary && Nth Highest Salary
- leetcode 176. Second Highest Salary
- leetcode 176. Second Highest Salary