您的位置:首页 > 其它

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组合进行查找。

所以开始答案是这样的:

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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: