How to find third or nᵗʰ maximum salary from salary table?

后端 未结 30 689
醉酒成梦
醉酒成梦 2020-11-30 16:30

How to find third or nth maximum salary from salary table(EmpID, EmpName, EmpSalary) in optimized way?

30条回答
  •  情歌与酒
    2020-11-30 17:19

    Find Nth highest salary from a table. Here is a way to do this task using dense_rank() function.

    select linkorder from u_links
    
    select max(linkorder) from u_links
    
    select max(linkorder) from u_links where linkorder < (select max(linkorder) from u_links)
    
    select top 1 linkorder 
           from ( select distinct top 2 linkorder from u_links order by linkorder desc) tmp 
    order by linkorder asc
    

    DENSE_RANK : 1. DENSE_RANK computes the rank of a row in an ordered group of rows and returns the rank as a NUMBER. The ranks are consecutive integers beginning with 1. 2. This function accepts arguments as any numeric data type and returns NUMBER. 3. As an analytic function, DENSE_RANK computes the rank of each row returned from a query with respect to the other rows, based on the values of the value_exprs in the order_by_clause. 4. In the above query the rank is returned based on sal of the employee table. In case of tie, it assigns equal rank to all the rows.

    WITH result AS ( 
         SELECT linkorder ,DENSE_RANK() OVER ( ORDER BY linkorder DESC ) AS  DanseRank 
    FROM u_links ) 
    SELECT TOP 1 linkorder FROM result WHERE DanseRank = 5
    

提交回复
热议问题