Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the 3rd Maximum Salary for each department based on table data

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?

The table structure is given below

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 

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
like image 259
bmsqldev Avatar asked Sep 22 '17 19:09

bmsqldev


People also ask

How can we find 3rd highest salary from table?

Here is a way to do this task using dense_rank() function. Query : select * from( select ename, sal, dense_rank() over(order by sal desc)r from Employee) where r=&n; To find to the 2nd highest sal set n = 2 To find 3rd highest sal set n = 3 and so on.

How do you find the maximum salary from a table?

To find the highest salary in the table, write the following query. SELECT MAX(SALARY) FROM Employee; This will give you the output as 15000, i.e the highest salary in the table above.


1 Answers

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

Returns

enter image description here

like image 53
John Cappelletti Avatar answered Oct 31 '22 05:10

John Cappelletti