代码之家  ›  专栏  ›  技术社区  ›  user379888

获得第n高薪

  •  3
  • user379888  · 技术社区  · 7 年前

    我想编写一个SQL查询,从 Employee 桌子

    +----+--------+
    | 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 回复  |  直到 7 年前
        1
  •  2
  •   Gurwinder Singh    7 年前

    您可以减小变量:

    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

        2
  •  0
  •   Rahul Gupta    6 年前

    从员工e1中选择不同的工资,其中2=(从员工e2中选择计数(不同的工资),其中e1。工资<=e2、工资);

        3
  •  0
  •   Hossein Golshani    6 年前

    这还将考虑存在空值或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