Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query to find nᵗʰ max value of a column

Tags:

sql

database

I want to find 2nd, 3rd, ... nth maximum value of a column.

like image 881
kiritsinh parmar Avatar asked Sep 17 '08 07:09

kiritsinh parmar


People also ask

How do I get the max value in a column in SQL?

To find the max value of a column, use the MAX() aggregate function; it takes as its argument the name of the column for which you want to find the maximum value. If you have not specified any other columns in the SELECT clause, the maximum will be calculated for all records in the table.

Which query can be used to extract the maximum value of the column?

SQL MIN() and MAX() Functions The MIN() function returns the smallest value of the selected column. The MAX() function returns the largest value of the selected column.

How do you find the max and min of a column in SQL?

To ask SQL Server about the minimum and maximum values in a column, we use the following syntax: SELECT MIN(column_name) FROM table_name; SELECT MAX(column_name) FROM table_name; When we use this syntax, SQL Server returns a single value.


2 Answers

Consider the following Employee table with a single column for salary.

 +------+ | Sal  | +------+ | 3500 |  | 2500 |  | 2500 |  | 5500 | | 7500 | +------+ 

The following query will return the Nth Maximum element.

select SAL from EMPLOYEE E1 where   (N - 1) = (select count(distinct(SAL))              from EMPLOYEE E2              where E2.SAL > E1.SAL ) 

For eg. when the second maximum value is required,

  select SAL from EMPLOYEE E1 where       (2 - 1) = (select count(distinct(SAL))                  from EMPLOYEE E2                  where E2.SAL > E1.SAL ) 
 +------+ | Sal  | +------+ | 5500 | +------+ 
like image 151
dexter Avatar answered Oct 02 '22 00:10

dexter


You didn't specify which database, on MySQL you can do

SELECT column FROM table ORDER BY column DESC LIMIT 7,10; 

Would skip the first 7, and then get you the next ten highest.

like image 35
Pieter Avatar answered Oct 02 '22 00:10

Pieter