How would you find the Nth highest salary in a table

Опубликовано: 30 Апрель 2024
на канале: Senior Classroom
64
8

How would you find the Nth highest salary in a table?

You can use a subquery with the DISTINCT keyword and ORDER BY clause. For example:

SELECT DISTINCT Salary FROM Employees ORDER BY Salary DESC LIMIT N-1, 1;

Let's break it down:

SELECT DISTINCT Salary: This selects all distinct salary values from the Employees table.

ORDER BY Salary DESC: This orders the salary values in descending order, so the highest salary comes first.

LIMIT N-1, 1: This limits the result to the (N-1)th row, starting from 0, and retrieves only one row. This effectively gives you the Nth highest salary.

For example, if you want to find the 3rd highest salary, you would replace N with 3, so it becomes:

SELECT DISTINCT Salary FROM Employees ORDER BY Salary DESC LIMIT 2, 1;

This query will return the 3rd highest salary from the Employees table.


Смотрите видео How would you find the Nth highest salary in a table онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь Senior Classroom 30 Апрель 2024, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 64 раз и оно понравилось 8 людям.