I want to find 2nd, 3rd, ... nth maximum value of a column.
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.
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.
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.
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 | +------+
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With