描述
Write a SQL query to get the second highest salary from the Employee
table.
1 | +----+--------+ |
For example, given the above Employee table, the $n^{th}$ highest salary where n = 2 is 200. If there is no $n{th}$ highest salary, then the query should return null.
分析
和上一题 176-Seconde-Highest-Salary 是相关联的
解决方案(MySQL)
比较容易想到的一个思路是先构造一个集合,把薪水最高的排除出去,这时候再选薪水最高的,就是 Employee 表中薪水第二高的了。
1 | CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT |
这里利用了 MySQL 的 limit,offset 关键字,limit 1 的意思是只筛选出一行,offset 1 的意思是从第2行开始,这里即选出表中薪水第二高的 Salary