0

I am trying to fetch record from empMaster table for the nth highest Salary.But getting error near 'N' .

SELECT TOP 1 salary
FROM 
    (SELECT DISTINCT TOP n salary 
     FROM empMaster
     ORDER BY salary DESC) AS temp
ORDER BY salary

Error message is:

Incorrect syntax near 'n'.

PoojaP
  • 1

3 Answers3

1

You can write query in SQL Server as given below:

DECLARE @n INT = 5
SELECT salary AS [nthSalary]
FROM
(
SELECT salary, ROW_NUMBER() OVER(ORDER BY salary DESC) AS rownum 
FROM empMaster) AS t
WHERE rownum = @n
Venkataraman R
  • 12,181
  • 2
  • 31
  • 58
0

SELECT TOP 1 Salary FROM (SELECT DISTINCT TOP N Salary FROM dbo.Employee ORDER BY Salary DESC) AS temp ORDER BY Salary

//* enter No of Highest salary in N Like 'N'=7 ( means 7th Highest salary) //*Incorrect syntax near 'n'. enter Numeric digit instead of 'n'

0

N will have some numeric value. So, use TOP (5) or TOP (@Nvariable).

You can use dense_rank to find highest salary employees :

select emp.*
from (select emp.*, 
             dense_rank() over (order by sal desc) as seq
      from empmaster emp
     ) emp
where emp.seq <= 5; -- Pass variable or change Nth value here

Dense_rank() will give you ties employees, meaning that if one or more employees have same salary then it will give you all.

Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52