How to find the employee with the second highest salary?(如何找到工资第二高的员工?)
问题描述
是否有任何预定义的函数或方法可用于从员工表中获取第二高的薪水?
Is there any predefined function or method available to get the second highest salary from an employee table?
推荐答案
实现这一点的方法是使用 Oracle 的分析功能.您的特定场景只是我在 另一个线程.
The way to do this is with Oracle's Analytic functions. Your particular scenario is just a variant on the solution I provided in another thread.
如果您只想选择第二高的薪水,那么 DENSE_RANK()、RANK() 和 ROW_NUMBER() 中的任何一个都可以:
If you are interested in just selecting the second highest salary then any of DENSE_RANK(), RANK() and ROW_NUMBER() will do the trick:
SQL> select * from
2 ( select sal
3 , rank() over (order by sal desc) as rnk
4 from
5 ( select distinct sal
6 from emp )
7 )
8 where rnk = 2
9 /
SAL RNK
---------- ----------
3000 2
SQL>
但是,如果您想选择附加信息,例如工资第二高的员工的姓名,您选择的函数会影响结果.选择一个而不是另一个的主要原因是当有平局时会发生什么.
However, if you want to select additional information, such as the name of the employee with the second highest salary, the function you choose will affect the result. The main reason for choosing one over another is what happens when there is a tie.
如果您使用 ROW_NUMBER() 它将返回按薪水排序的第二个员工:如果有两个员工并列最高薪水怎么办?如果有两名员工并列第二高的工资怎么办?如果您使用 RANK() 并且有两名员工并列第一个最高工资,则 没有 RANK = 2 的记录.
If you use ROW_NUMBER() it will return the second employee ordered by salary: what if there are two employees tying for the highest salary? What if there are two employees tying for the second highest salary? Wheareas if you use RANK() and there are two employees tying for first highest salary, there will be no records with RANK = 2.
我建议 DENSE_RANK() 通常是在这些情况下选择的最安全的函数,但它确实取决于特定的业务需求.
I suggest DENSE_RANK() is the usually the safest function to choose in these cases, but it really does depend on the specific business requirement.
这篇关于如何找到工资第二高的员工?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何找到工资第二高的员工?
基础教程推荐
- 带更新的 sqlite CTE 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
