How to get nᵗʰ highest value using plain SQL

前端 未结 8 1084
孤城傲影
孤城傲影 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条回答
  •  爱一瞬间的悲伤
    2021-01-25 00:20

    You have to incur the overhead of sorting, and in my example rownum is the sorted row number, not the physical location.

    Since everyone is using analytic functions to show how this works here is one:

       select foo,bar, max(baz)  
        from  
        (
           select *   
          from  
          (  
              select foo,bar,baz, row_number() over 
              (partition by some_identifier_that_Groups order by  value DESC) rn 
          )    
           where rn = 1  -- get the highest value for each partition    
        ) group by foo,bar
    

提交回复
热议问题