如何使用单个查询显示最高薪水和第二高薪

时间:2016-07-21 08:23:01

标签: sql oracle

如何使用单个查询显示sql中employee表的最高薪水和第二高薪?

3 个答案:

答案 0 :(得分:1)

使用rownum pseudocolumn https://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns009.htm#i1006297

with emp(emp_id, salary) 
  as (select 1, 1000 from dual union
      select 2, 3000 from dual union 
      select 3, 5000 from dual)

select * 
  from (select * 
         from emp
        order by salary desc) 
 where rownum <=2

输出

    EMP_ID     SALARY
---------- ----------
         3       5000 
         2       3000 

答案 1 :(得分:0)

简短回答您的简短问题是:

SELECT salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 2 ROWS ONLY

答案 2 :(得分:0)

select empid, salary, rn
from (
    select empid, salary , rank() over(order by salary desc) as rn
     from emp) t
where rn<=2;