在MySQL中不使用“LIMIT”查找第4或第n个最高薪水

时间:2016-01-27 05:35:55

标签: mysql sql

要获得我用过的第4个最高薪水,但这不起作用,请帮我解决MySQL中的其他问题。

SELECT *
   FROM employee e1
   WHERE ( 4 ) = ( SELECT COUNT( e2.salary )
                   FROM employee e2
                   WHERE e2.salary >= e1.salary
                 )

3 个答案:

答案 0 :(得分:2)

不是非常有效,但应该有效:

SET @i=0;
SET @N=4;
SELECT * 
FROM (SELECT *, (@i:=@i+1) As num
      FROM Employee
      WHERE @i <= @N
      ORDER BY salary) al
WHERE num = @N;

DEMO

答案 1 :(得分:0)

六个月前我在leetcode找到了同样的问题。

员工表:

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

以下是我如何解决它:

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
SET @count := N;
  RETURN (
      # Write your MySQL query statement below.


        SELECT tt.Salary
        FROM 

        (

                SELECT (@count := @count -1) AS c,t.Salary

                FROM 
                (
                    SELECT

                        Salary
                    FROM
                        Employee
                    GROUP BY Salary
                    ORDER BY
                        Salary DESC
                ) AS t
                WHERE @count >=1

        ) AS tt

        WHERE tt.c=0

  );
END

这里提取的查询:

SET @count := N;
    SELECT tt.Salary
                FROM 

                (

                        SELECT (@count := @count -1) AS c,t.Salary

                        FROM 
                        (
                            SELECT

                                Salary
                            FROM
                                Employee
                            GROUP BY Salary
                            ORDER BY
                                Salary DESC
                        ) AS t
                        WHERE @count >=1

                ) AS tt

                WHERE tt.c=0

<强>说明

  1. getNthHighestSalary是一个采用整数的过程 参数并返回第N个最高薪水。
  2. 首先将变量计数设置为N。
  3. 最内部选择查询按降序对工资进行排序。所以 最高薪水排在第一行。
  4. 从这个结果集中,如果你向下走N步并停下来就会得到 第N个最高薪水。
  5. 这就是结果。

答案 2 :(得分:0)

使用以下查询 -

SELECT salary 
FROM employee AS t1 
WHERE 4 =  
(
SELECT COUNT(DISTINCT salary) 
FROM employee AS t2 
WHERE t1.salary<=t2.salary
) GROUP BY t1.salary;