Mysql中的行号函数,面临Order by子句的问题

时间:2018-03-07 13:53:35

标签: mysql row-number

数据:

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

我正在尝试使用以下代码获得Nth最高薪水。 例如,如果我通过" N"值为1,下面的代码给我100,而它应该是300.我不知道为什么"顺序由desc"工作不正常。

CREATE FUNCTION gethighestsalary(N INT) RETURNS INT
BEGIN
DECLARE rank INT;
SET @rank = 0;
RETURN (
select a.salary FROM (select salary, @rank:=@rank+1 as chk from Employee group by salary order by salary desc) AS a
where a.chk= N
);
END

2 个答案:

答案 0 :(得分:0)

删除group by

select a.salary, a.chk
FROM 
(  
    select salary, @rank := @rank + 1 as chk 
    from t 
    cross join (select @rank := 0) r
    order by salary desc
) AS a
where a.chk = 1

SQLFiddle demo

否则order by将无效,因为它在分组后排序,然后您的行号错误。

或者保持分组并将其放入另一个子查询中并在之后排名。

答案 1 :(得分:0)

以下代码对您有所帮助,

SELECT Salary FROM Employee Emp1 
WHERE (N-1) = ( 
                SELECT COUNT(DISTINCT(Emp2.Salary)) 
                FROM  Employee Emp2
                WHERE Emp2.Salary > Emp1.Salary
              )

SQL Fiddle Demo