获得第n个最高薪水

时间:2017-10-15 15:27:49

标签: mysql

我想写一个SQL查询来从Employee表中获得第n个最高薪水。

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

我尝试了什么?

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
  );
END

问题: 我希望返回行N-1而不是N,因为行从0开始。我试图设置一个变量,但它不起作用,

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

3 个答案:

答案 0 :(得分:1)

你可以减少变量:

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  set n = n - 1;
  RETURN (
      # Write your MySQL query statement below.
      SELECT Salary
        FROM Employee
        ORDER BY Salary desc
        Limit n, 1
  );
END;

如果必须使用单独的var,请先声明它:

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  declare m int;
  set m = n - 1;
  RETURN (
      # Write your MySQL query statement below.
      SELECT Salary
        FROM Employee
        ORDER BY Salary desc
        Limit m, 1
  );
END;

Demo

答案 1 :(得分:0)

从员工e1中选择DISTINCT薪水,其中2 =(从员工e2中选择计数(DISTINCT薪水),其中e1.salary< = e2.salary);

其中2 =数字。您可以从员工表中找到任何最高薪水。比如3rd,然后用3替换2。

答案 2 :(得分:-1)

这还将考虑存在空值或2个相同最高薪水的情况

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
declare m int;
set m = n-1;
  RETURN (SELECT DISTINCT Salary AS getNthHighestSalary
      FROM Employee
      ORDER BY Salary DESC
      LIMIT m, 1

  );
END