Get second highest value in a table
To get the second highest distinct value in the table you can use
SELECT MIN(value)
FROM (SELECT DISTINCT TOP (2) value
FROM tablename
ORDER BY value DESC)T
/*If only one distinct value return nothing. */
HAVING MIN(value) <> MAX(value);
Assuming the highest value only occurs once, another way would be to use OFFSET
(SQL Server 2012 or later):
SELECT *
FROM tablename
ORDER BY column DESC
OFFSET 1 ROW
FETCH NEXT 1 ROW ONLY;
A generic solution can be like below:
;WITH CTE AS
(
SELECT
Col1
, Col2
, <AnyColumns>
, ROW_NUMBER() OVER (ORDER BY <AnyColumns>) AS RowNum
FROM <YourTable>
WHERE <YourCondition>
)
SELECT *
FROM CTE
WHERE RowNum = 2 -- Or any condition which satisfies your problem
Here you can also define the range like RowNum >= 10 AND RowNum <= 20
. And it will give you 10th to 20th rows with all required columns.