Sql Server 2005

Tuesday, May 24, 2005

How to find Second Maximum value from the table

Sometimes we require to find the Second Maximum values form the table.

Lets takes an examples where we need to find the second max Salary of an employee.

This requires some round work as there is no direct way to get the Second-Max, as in the case of getting the Max value.

Different queries that we can use are as follows:

1)
select max(sal) from table where sal < (select max(sal) from table)

2)
Select min(sal) from table where sal in (select top 2 sal from table order by sal desc)

In the first case, u get the max salary again check out for the max salary less then that value. While in the 2nd case u get the two most paid person and then take the minimum value of the two.