SQL select top earners by department

By   Tewodros   Date Posted: Sep. 28, 2021  Hits: 1,123   Category:  Database   Total Comment: 0             A+ A-


side

Given the above table definitions, write a SQL query to find employees who earn the top three salaries in each of the department.

Here we need to use Dense_Rank() function that will basically rank the employees based on salary after partitioning with department ID. 

Dense_Rank() over(partition by E.DepartmentId order by E.salary desc) as Rank

Then we can use subquery to get only top three earners.

 

 

Select Department,Employee,salary  

from (

select D.Name as Department, E.name as Employee, E.salary,

 Dense_Rank() over(partition by E.DepartmentId order by E.salary desc) as Rank

from employee E join Department D

on E.DepartmentId =D.Id

) as topearners where Rank <=3


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* stjwmc

Back to Top