ORACLE SQL第二最高工资

时间:2017-12-29 06:02:30

标签: sql oracle top-n

如何查找员工从员工表中提取的第二个最高薪水。是否可以通过ROWNUM功能找到它。

示例表:

S.no    Name       employee_id     salary
201     Steven        100            1000
202     Alexander     101            2500 
203     Daniel        102            5000
204     John          103            3000
205     Ishanth       104            8000 

5 个答案:

答案 0 :(得分:2)

既然你提到了第二高的薪水,你应该使用DENSE_RANK而不是ROW_NUMBER如果有两个具有相同最高价值的员工,即使你提供的话也会错误地给你最高工资WHERE ROW_NUMBER = 2条件。

SELECT A.S_NO, A.NAME, A.EMPLOYEE_ID, A.SALARY
FROM
    (SELECT S_NO, NAME, EMPLOYEE_ID, SALARY, 
     DENSE_RANK() OVER (ORDER BY SALARY DESC) AS SALARY_RANK) A
WHERE A.SALARY_RANK = 2;

答案 1 :(得分:0)

试试这个

SELECT salary FROM (SELECT DISTINCT salary FROM Employees  ORDER BY salary 
DESC) WHERE ROWNUM=2;

其中,

  • salary是列名称
  • Employees是表名

获取第二个最高工资的最简单方法第n个工资

select 
 DISTINCT(salary) 
from Employees 
 order by salary desc 
limit 1,1

注意:

limit 0,1  - Top max salary

limit 1,1  - Second max salary

limit 2,1  - Third max salary

limit 3,1  - Fourth max salary

更新oracle

SELECT salary FROM (
    SELECT salary, row_number() OVER (order by salary desc) AS rn FROM Employees
)
WHERE rn = 2

答案 2 :(得分:0)

我想,你可以在这里使用Nth_Value函数 有关语法

,请参阅https://docs.oracle.com/cloud/latest/db112/SQLRF/functions114.htm#SQLRF30031
select distinct 
nth_value(salary,2) OVER (ORDER BY salary desc range between unbounded preceding and unbounded following) as secondVal 
from HR.EMPLOYEES;

另一种选择是使用DENSE_RANK函数,如下所示

with cte as (
    select salary, dense_rank() over (order by salary desc) as nth_salary from Employee
)
select salary from cte 
where 
    nth_salary = 2;

这是输出

enter image description here

答案 3 :(得分:0)

对最高工资使用一般查询:

select salary from table_name order by salary desc limit n-1,1;

答案 4 :(得分:0)

而不是使用ROWNUM。您可以轻松找到' n'

的工资
SELECT *
  FROM (
  SELECT DISTINCT  salary 
  FROM Employees
  ORDER BY salary DESC limit 2
  ) a
ORDER BY a.salary limit 1

此处代替" 2"你可以给任何" n"你需要的价值。