sql从表中获得第N个最高薪水

时间:2015-01-11 16:26:18

标签: mysql sql database greatest-n-per-group

编写SQL查询以从Employee表中获得第n个最高薪水。

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

例如,给定上面的Employee表,n = 2的第n个最高工资是200.如果没有第n个最高工资,那么查询应该返回null。

我的回答

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  RETURN (

      # Write your MySQL query statement below.
    SELECT Salary FROM Employee ORDER BY Salary DESC LIMIT N-1, 1

  );
END

错误:

Runtime Error Message:  Line 6: SyntaxError: near '-1, 1 ); END'
Last executed input:    {"headers": {"Employee": ["Id", "Salary"]}, "argument": 1, "rows": {"Employee": [[1, 100]]}}

1 个答案:

答案 0 :(得分:0)

DELIMITER $
CREATE FUNCTION salarynth(n1 INT)
  RETURNS INT
   DETERMINISTIC
    BEGIN  
     DECLARE myvar INT;  
     SELECT 
SUBSTRING_INDEX(SUBSTRING_INDEX(CONCAT(group_concat(salary order by id),','), ',', n1),',',-1) INTO myvar FROM t;
     RETURN myvar;
    END$
DELIMITER ;


SELECT `salarynth`('3');

300