If you need a whole row (all columns), it will do this. In addition, it will always return only one row, even if there are several with the same 2nd maximum value.
Select top 1 *
From (Select Top 2 *
From TABLE
Order By marks desc
) a
Order By marks asc
If you only need one line with a real 2nd maximum value, you should use:
select Top 1 *
from TABLE
where marks < (select max(marks) from TABLE)
Order by max desc
This can also be done using CTE (SQL Server 2005+):
;With a as
(
Select Dense_Rank() over (order by marks desc) as nRank,
*
From TABLE
)
Select Top 1 *
from a
Where nRank=2
If you want to see all rows with second maximum marks, simply remove TOP 1 from the previous query.
source
share