我需要找出table
中每个部门的员工的3rd maximum salary
。如果不存在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
我试图获得最大的薪水为每个类别使用row_number
功能的常见方式给出。
;with cte
as
(
select ROW_NUMBER() over(partition by deptid order by salary) as id, * from employee1
)
select * from cte
如果什么有关系?你想要两条记录吗?在这种情况下,如果1人的薪水最高,2人并列第二名,那么你想要第三最高薪水(第四人)还是第二人? – Matt
是啊..我会将row_number更改为dense_rank来解决关系。 – bmsqldev
我更新了答案,你只需要用dense_rank()替换row_number() – Matt