要获得我用过的第4个最高薪水,但这不起作用,请帮我解决MySQL中的其他问题。
SELECT *
FROM employee e1
WHERE ( 4 ) = ( SELECT COUNT( e2.salary )
FROM employee e2
WHERE e2.salary >= e1.salary
)
答案 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;
答案 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
<强>说明强>
答案 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;