Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Query to find 3 highest paid people in each department

create table employees(id int PRIMARY KEY, name varchar(30),salary int,department_id int);

insert into employees values(1,'ruchi',10000,2);
insert into employees values(2,'ritu',7000,2);
insert into employees values(3,'rima',7000,2);
insert into employees values(4,'koel',5000,1);
insert into employees values(5,'huma',2000,1);
insert into employees values(6,'manav',4500,1);
insert into employees values(7,'sayan',3500,1);
insert into employees values(8,'shrey',9000,2);
insert into employees values(9,'garima',1000,2);

I want to get the top 3 highest paid employees in each department.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can do it using row_number() function to order your data by salary :

with cte as (
  select *, row_number() over(partition by department_id order by salary desc) as rn
  from employees
)
select id, name, salary, department_id
from cte
where rn <= 3
order by department_id, rn asc;

Demo here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading