标题3:MySQL-Nth Highest Salary

题目3:MySQL----------Nth Highest Salary

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.

题目解答:

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
DECLARE M INT;
SET M=N-1;
  RETURN (
      # Write your MySQL query statement below.
      SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT M, 1
  );
END






2楼mchdba昨天 22:07
有需要这么复杂吗?nSELECT max(Salary) FROM Employee ; 不就OK了啊。
Re: chenxun2009昨天 22:08
回复mchdbanthe n highest salary......
Re: mchdba11小时前
回复chenxun2009n就是分组求每组的最大值,是吧?
Re: chenxun200911小时前
回复mchdban真的吗,你有没有考虑重复值还有其他问题,仔细分析问题啊,不要太暴力了哦..........
Re: mchdba1小时前
回复chenxun2009nn嘿嘿,分组的同时用max函数就是唯一值了吧,不知道你描述的是否是这种情况啊?
1楼mchdba前天 09:33
我看你return里面的返回值就是Salary 这个字段值,所以分组再max可以了吧?
Re: chenxun2009昨天 16:55
回复mchdban求第n个
Re: mchdba昨天 20:48
回复chenxun2009n第一个分组中第N个薪水高的是吧?
Re: chenxun2009昨天 23:42
回复mchdban建议你自己创建不同情况的表试试。