Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something equivalent to argmax in SQL?

Tags:

sql

In a more general sense: is there a function that will allow me to find the entire row where a value in Column X is the max value of the column?

like image 935
Christine Avatar asked Dec 29 '10 18:12

Christine


People also ask

Can you do max on SQL?

SQL Server MAX() function is an aggregate function that returns the maximum value in a set. The MAX() function accepts an expression that can be a column or a valid expression. Similar to the MIN() function, the MAX() function ignores NULL values and considers all values in the calculation.

How do you get the max number 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.

What is Max string in SQL?

The maximum length of an SQL statement string is 65,000 characters.


2 Answers

Not a specific function, no.

There are numerous ways to write the query, depending on needs and what functionality is supported by the database.

The Subquery:

This approach risks returning more than one row if any share the same value:

SELECT x.*   FROM YOUR_TABLE x  WHERE x.column = (SELECT MAX(y.column)                      FROM YOUR_TABLE y) 

The Self Join:

This approach risks returning more than one row if any share the same value:

SELECT x.*   FROM YOUR_TABLE x   JOIN (SELECT MAX(t.column) AS max_col           FROM YOUR_TABLE t) y ON y.max_col = x.column 

LIMIT/TOP:

SQL Server supports TOP:

  SELECT TOP 1           x.*     FROM YOUR_TABLE x ORDER BY x.column DESC 

MySQL & PostgreSQL support LIMIT:

  SELECT x.*     FROM YOUR_TABLE x ORDER BY x.column DESC    LIMIT 1 

Analytic - ROW_NUMBER():

This will return one row, and can be configured to provide the highest (or lowest) value per grouping. However, this functionality is Oracle 9i+, SQL Server 2005+, and PostgreSQL 8.4+.

SELECT x.*   FROM (SELECT y.*,                ROW_NUMBER() OVER (ORDER BY y.column DESC) AS rank           FROM YOUR_TABLE y) x  WHERE x.rank = 1  

Analytic - DENSE_RANK():

This can return multiple rows if they share the same value, and can be configured to provide the highest (or lowest) value per grouping. However, this functionality is Oracle 9i+, SQL Server 2005+, and PostgreSQL 8.4+.

SELECT x.*   FROM (SELECT y.*,                DENSE_RANK() OVER (ORDER BY y.column DESC) AS rank           FROM YOUR_TABLE y) x  WHERE x.rank = 1  
like image 172
OMG Ponies Avatar answered Oct 09 '22 02:10

OMG Ponies


SELECT * FROM mytable WHERE mycolumn = (   SELECT MAX(mycolumn) FROM mytable ) 
like image 28
Oswald Avatar answered Oct 09 '22 04:10

Oswald