How to get second largest or third largest entry from a table

前端 未结 12 2453
说谎
说谎 2020-12-01 08:42

Can anyone please tell me how to find out the N th largest entry from a table in Oracle?

Like for largest we can use MAX(column_name) i

相关标签:
12条回答
  • 2020-12-01 09:01

    Try this,

    SELECT Sal FROM Tab ORDER BY Sal DESC LIMIT 2,1
    
    0 讨论(0)
  • 2020-12-01 09:02

    You can find the Nth largest value of a column by using the following query

    SELECT * 
    FROM TableName a 
    WHERE n = (
               SELECT count( DISTINCT (b.ColumnName) )
               FROM TableName b 
               WHERE a.ColumnName <= b.ColumnName 
              );
    
    0 讨论(0)
  • 2020-12-01 09:16

    I think the below query will work to find the second highest record with NOT IN.

    SELECT MAX( userId )
    FROM table 
    WHERE userId NOT IN ( 
                          SELECT MAX( userId )
                          FROM table
                        ); 
    

    simple and useful...

    0 讨论(0)
  • 2020-12-01 09:16
    SELECT MAX(Salary) FROM Employee
    WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee)
    
    0 讨论(0)
  • 2020-12-01 09:17
    SELECT *
    FROM (
      SELECT some_column, 
             row_number() over (order by your_sort_column desc) as row_num
      FROM some_table
    ) t
    WHERE row_num = 3
    


    If you expect more than one row to have the same value in your_sort_column you can also use the rank() function

    SELECT *
    FROM (
      SELECT some_column, 
             rank() over (order by your_sort_column desc) as row_rank
      FROM some_table
    ) t
    WHERE row_rank = 3
    
    This migh return more than one row..

    0 讨论(0)
  • 2020-12-01 09:18

    It works for second highest salary,

    $query = "SELECT * FROM `table_name` ORDER BY field_name` DESC LIMIT 1 , 1 "; 
    
    0 讨论(0)
提交回复
热议问题