用于查找次高的SQL

时间:2013-03-07 19:00:02

标签: sql

说我有一份员工表,我在一栏中保留员工的姓名,另一栏列出员工的薪水。应该写什么SQL来找到绘制第二高工资的员工的姓名???

3 个答案:

答案 0 :(得分:2)

我会使用row_number()

select e.*
from (select e.*, row_number() over (order by salary desc) as seqnum
      from employees e
     ) e
where seqnum = 1

其他人提到了limit / top / rownum方法:

select e.*
from (select e.*
      from employees e
      order by salary desc
      limit 2
     ) t
order by salary
limit 1

你可以用偏移做同样的事情:

select e.*
from employees e
order by salary desc
limit 2, 1

然而,如果你有最高工资的平局,所有都有问题。通过将row_number()替换为dense_rank()

,可以轻松修复第一种方法
select e.*
from (select e.*, dense_rank() over (order by salary desc) as seqnum
      from employees e
     ) e
where seqnum = 1

而另一种方法是:

select e.*
from employees e
where e.salary < (select max(salary) from employees)
order by salary desc
limit 1  -- or top 1 or rownum = 1 etc.

答案 1 :(得分:1)

您可以尝试从“前2名”中选择,按升序排序,然后选择“前1名”,这样可以为您提供正确的行。

答案 2 :(得分:0)

您可以执行以下操作:

select * from (select * from Employees order by salary desc limit 2) as A order by salary asc limit 1;