bms*_*dev 5 sql t-sql sql-server
我需要3rd maximum salary为a中的每个部门找到一个员工table.如果不3rd maximum salary存在则显示2nd maximum salary.如果不2nd maximum salary存在则找到highest salary.如何实现这个结果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
Run Code Online (Sandbox Code Playgroud)
我尝试了使用row_number函数获得每个类别的最高工资的常用方法.
;with cte
as
(
select ROW_NUMBER( ) over( partition by deptid order by salary) as id, * from employee1
)
select * from cte
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
退货