Skip to content
Advertisement

How to apply this query to all the employees

I have a query to compute the 3rd highest salary for an employee as shown below.

How can I apply this query to give the 3rd highest salary for each employee which can be fetched by the query

Note: without using special functions like dense_rank()

Advertisement

Answer

You are looking for each employee’s third highest salary. It can happen that we find the same salary for an employee multiple times in the table, as your sample data shows. So, make the salaries per employee distinct, then rank the rows with ROW_NUMBER, RANK or DENSE_RANK (which doesn’t matter with distinct values) and then pick the third ranked.

An alternative would be to count higher salaries in a subquery and select those salaries where exist two higher salaries for the employee:

Demo: https://dbfiddle.uk/?rdbms=postgres_14&fiddle=1e17669870f2e9c7f5867bf2ee6c24bf

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement