What is the simplest way to get the nth highest value from a result set using plain SQL?
The result set would be huge, thus need to consider performance too.>
This is the T-SQL (SQL-Server 2005 and greater) approach using ROW_NUMBER:
WITH CTE AS
(
SELECT
Col1, Col2, ValueCol,
RN = ROW_NUMBER() OVER (ORDER BY ValueCol DESC) -- change to ASC if you want lowest first
FROM
dbo.TableName
)
SELECT
Col1, Col2, ValueCol
FROM
CTE
WHERE
RN = @nthhighestvalue
If you want all rows with the same value use DENSE RANK instead.
Difference between ROW_NUMBER, RANK and DENSE_RANK