How to get nᵗʰ highest value using plain SQL

前端 未结 8 1174
孤城傲影
孤城傲影 2021-01-24 23:42

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.

8条回答
  •  萌比男神i
    2021-01-25 00:25

    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

提交回复
热议问题