"how to fetch the nth highest salary from a table without using top and sub-query?" Code Answer

3

try a cte - common table expression:

with salaries as
(
    select 
       salaryamount, row_number() over(order by salaryamount desc) as 'rownum'
    from 
       dbo.salarytable
)
select
  salaryamount
from
  salaries
where
   rownum <= 5

this gets the top 5 salaries in descending order - you can play with the rownumn value and basically retrieve any slice from the list of salaries.

there are other ranking functions available in sql server that can be used, too - e.g. there's ntile which will split your results into n groups of equal size (as closely as possible), so you could e.g. create 10 groups like this:

with salaries as
(
    select 
       salaryamount, ntile(10) over(order by salaryamount desc) as 'ntile'
    from 
       dbo.salarytable
)
select
  salaryamount
from
  salaries
where
   ntile = 1

this will split your salaries into 10 groups of equal size - and the one with ntile=1 is the "top 10%" group of salaries.

By rciq on April 9 2022

Answers related to “how to fetch the nth highest salary from a table without using top and sub-query?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.