为有牺牲多壮志,敢教日月换新天。

[SQL]LeetCode177. 第N高的薪水 | Nth Highest Salary

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10145510.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

Write a SQL query to get the nth highest salary from the Employee table.

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

For example, given the above Employee table, the nth highest salary where n = 2 is 200. If there is no nth highest salary, then the query should return null.

+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200                    |
+------------------------+

编写一个 SQL 查询,获取 Employee 表中第 高的薪水(Salary)。

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

例如上述 Employee 表,n = 2 时,应返回第二高的薪水 200。如果不存在第 高的薪水,那么查询应返回 null

+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200                    |
+------------------------+

140ms
1 CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
2 BEGIN
3     set N = N-1;
4   RETURN (
5       # Write your MySQL query statement below.
6       select distinct Salary from Employee order by Salary desc limit N,1
7   );
8 END

149ms

 1 CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
 2 BEGIN
 3   set N = N-1;
 4   RETURN (      
 5       select distinct Salary as 'getNthHighestSalary(2)'
 6       from Employee
 7       order by Salary desc
 8       limit N, 1
 9   );
10 END

 

posted @ 2018-12-19 19:49  为敢技术  阅读(431)  评论(0编辑  收藏  举报