Find the 3rd Maximum Salary for each department based on table data(根据表格数据找到每个部门的第三个最高工资)
问题描述
我需要在表
中找出每个部门员工的第三个最高工资
.如果不存在第三个最高工资
,则显示第二个最高工资
.如果不存在第二个最高工资
,则找到最高工资
.如何在sql-server
中实现这个结果?
I need to find out the 3rd maximum salary
for an employee for each department in a table
. if no 3rd maximum salary
exists then display 2nd maximum salary
. if no 2nd maximum salary
exist then find the highest salary
. How to achieve this result in sql-server
?
table
结构如下
create table employee1(empid int, empname varchar(10), deptid int, salary money)
insert into employee1
select 1,'a',1, 1000
union
select 1,'b',1, 1200
union
select 1,'c',1, 1500
union
select 1,'c',1, 15700
union
select 1,'d',2, 1000
union
select 1,'e',2, 1200
union
select 1,'g',3, 1500
我已经尝试了使用 row_number
函数获取每个类别最高工资的常用方法.
I have tried the common way of getting the maximum salary for each category using row_number
function.
;with cte
as
(
select ROW_NUMBER( ) over( partition by deptid order by salary) as id, * from employee1
)
select * from cte
推荐答案
Select EmpID,empname,deptid,salary
From (
Select *
,RN = Row_Number() over (Partition By deptid Order By Salary)
,Cnt = sum(1) over (Partition By deptid)
From employee1
) A
Where RN = case when Cnt<3 then Cnt else 3 end
退货
这篇关于根据表格数据找到每个部门的第三个最高工资的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:根据表格数据找到每个部门的第三个最高工资


- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- SQL 临时表问题 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 更改自动增量起始编号? 2021-01-01