Friday, September 30, 2011

Find the Nth Highest Salary record in Sql Server 2005

This is one of the very basic SQL query asked by most of the Interviewers.
This goes like....

Select Top 1 * from
(
Select Top N *  from dbo.Table Order By Table .Salary Desc
)  a
Order By Table .Salary Asc
This query is only valid if there are no multiple entries.

for multiple entries the dence_rank() function may hold good

Select dence_rank() over(order by salary desc) as rank   from dbo.Table  where rank=n

1 comment:

  1. Hi Friends,
    To my above post, I would like to add that the above statement is only valid when there are no multiple value entries in the Table.

    if there is then the sql Server Dense_Rank() function will work perfect.

    ReplyDelete