码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Nth Highest Salary

时间:2015-04-13 09:35:04      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:leetcode   sql   database   postgresql   

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.

注意相同的salary算一位,而且limit以及offset不能用表达式,至少我写的时候是不行的。

一开始不知道如何声明一个变量,结果硬是写了这个方法:

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  RETURN (
      select(select a.salary from(select distinct b.salary from Employee b union all select max(c.salary) from Employee c)a order by a.salary desc limit 1 offset N)
  );
END
后来在discuss看到了如何声明变量:

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
declare M int;
set M = N - 1;
  RETURN (
      select distinct salary from Employee order by salary desc limit 1 offset M
  );
END

LeetCode Nth Highest Salary

标签:leetcode   sql   database   postgresql   

原文地址:http://blog.csdn.net/u012925008/article/details/45015337

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!