views:

75

answers:

2

For Finding nth highest salary I am using

select salary from 
  (
   select distinct ROW_NUMBER() over (order by salary desc) as rownum,Salary
   from Employee
  )a
  where rownum=2

However if i have same salary like

70000
70000
60000
50000
50000

When executing the query i am getting second highest salary

70000 instead 60000 

how to avoid duplicates?

+3  A: 

It's the salaries that must be distinct, not the row numbers:

SELECT salary FROM
(
    SELECT ROW_NUMBER() OVER (ORDER BY salary DESC) AS rownum, salary
    FROM (SELECT DISTINCT Salary FROM Employee) T1
) T2
WHERE rownum=2
Mark Byers
+3  A: 

Although Mark has already provided one answer, I'd say that you're using the wrong function. You don't want the row number, you want the RANK. And based on how you want to handle duplicates, specifically you should be using DENSE_RANK.

E.g.:

SELECT salary FROM
(
    SELECT DENSE_RANK() OVER (ORDER BY salary DESC) AS rank, salary
    FROM Employee
) T2
WHERE rank=2
Damien_The_Unbeliever
Thank you Damien for you clarification
Gopi
+1 I agree. This is the correct way to do it.
Mark Byers