Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch the nth highest salary from a table without using TOP and sub-query?

Recently in an interview I was asked to write a query where I had to fetch nth highest salary from a table without using TOP and any sub-query ?

I got totally confused as the only way I knew to implement it uses both TOP and sub-query.

Kindly provide its solution.

Thanks in advance.

like image 995
HotTester Avatar asked Sep 05 '10 08:09

HotTester


People also ask

How do you get the nth highest salary from the employee table without a subquery?

Select Emp_name from table_name where Salary =( Select Salary from table_name order by Salary DESC limit n-1,1); There can be another question like find Nth Lowest Salary .

How can we find nth highest salary in each department in SQL Server?

The NTH_VALUE() function explicitly shows you the value of the third-highest salary by department. The ROW_NUMBER() , RANK() , and DENSE_RANK() functions rank the salaries within each department. Then, you can simply find the salary value associated with rank number 3.


2 Answers

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.

like image 137
marc_s Avatar answered Sep 22 '22 13:09

marc_s


;with cte as(
Select salary,
row_number() over (order by salary desc) as rn
from salaries
)

select salary 
from cte 
where rn=@n

(or use dense_rank in place of row_number if you want the nth highest distinct salary amount)

like image 42
Martin Smith Avatar answered Sep 18 '22 13:09

Martin Smith