Skip to content
Advertisement

Selecting the record(s) with the “second” highest something

I have written the following SQL commands for retrieving data from a table called Employee.

I was able to get the highest/maximum salary as well as the second highest/maximum salary, but I am having difficulty writing the same when the whole record needs to be returned.

enter image description here

Select all the employees.

Return the highest salary. This returns the maximum salary amount which is 90000

Return the employee record with the highest salary. This returns all the records of the person/people with their salary being the maximum salary which is 90000 that is only John Henry in this case.

Return every other employee record; i.e. everyone except the one with the highest salary.

Return the second highest salary. This returns the second maximum salary amount which is 85000

Return the employee record with the second highest salary. This returns all the records of the person/people with their salary being the second maximum salary which is 85000 that is only Michael Greenback in this case.

I am stuck in this… I tried using HAVING as an extra condition, but however I arrange it to specify a condition, I get syntax errors. How do I do this?

Advertisement

Answer

Window functions are the built-in functionality to do this. In particular, dense_rank():

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