Query to find 2nd top salary in each department

Conventional Query:

select 
    department_id, 
    last_name, 
    salary
from employees e
where 1 = (select count(distinct salary) 
                    from employees e2 
                    where e2.salary > e.salary and e2.department_id = e.department_id)
order by department_id;




Analytical Query:
Select department_id, last_name, salary
from (select e.department_id, last_name, salary, 
            dense_rank() over (partition by department_id order by salary desc) rank
            from employees e)
where rank = 2    
order by department_id;



No comments:

Post a Comment