gpt4 book ai didi

sql - 根据表格数据找到每个部门的第三个最高工资

转载 作者:行者123 更新时间:2023-12-02 22:45:51 24 4
gpt4 key购买 nike

我需要在中找出每个部门的员工的第三个最高工资。如果不存在第三最高工资,则显示第二最高工资。如果不存在第二最高工资,则查找最高工资。如何在sql-server中实现这个结果?

结构如下所示

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函数获取每个类别的最高工资的常见方法。

;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

返回

enter image description here

关于sql - 根据表格数据找到每个部门的第三个最高工资,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46371935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com