0

假设我有一张员工表,我在其中一列中维护员工的姓名,在另一列中维护他们提取的薪水。我应该写什么 SQL 来找到获得第二高薪水的员工的名字???

4

3 回答 3

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//方法toprownum

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.
于 2013-03-07T19:26:39.897 回答
1

您可以尝试从“Top 2”中选择,按升序排序,然后是“Top 1”,它应该为您提供正确的行。

于 2013-03-07T19:02:39.390 回答
0

您可以执行以下操作:

select * from (select * from Employees order by salary desc limit 2) as A order by salary asc limit 1;
于 2013-03-07T19:03:23.537 回答