Wednesday, 16 October 2019

find out nth highest salary of the employee using sql query


How to find out 2nd highest salary of the employee using sql query

SELECT t.salary
FROM (
      SELECT salary,
          DENSE_RANK() OVER (ORDER BY SALARY DESC) AS dense_rank
      FROM employees
      ) as t 
WHERE t.dense_rank = 2

This above query will get you the 3rd highest salary in the individual department. If you want regardless of the department, then just remove PARTITION BY department_id

SELECT department_id, salary, RANK1 FROM (
    SELECT department_id,
           salary,
           DENSE_RANK ()
              OVER (PARTITION BY department_id ORDER BY SALARY DESC)
              AS rank1
    FROM employees) result 
WHERE rank1 = 3

No comments:

Post a Comment