Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get row with highest or lowest value from a GROUP BY

Tags:

I'm trying to get the row with the highest/lowest number, after performing a GROUP BY:

Here is my test data

mysql> SELECT * FROM test; +----+-------+------+ | id | value | name | +----+-------+------+ |  1 |    10 | row1 | |  2 |    12 | row2 | |  3 |    10 | row2 | |  4 |     5 | row2 | +----+-------+------+ 4 rows in set (0.00 sec) 

To get the lowest value, I'll use MIN()

mysql> SELECT id, name, MIN(value) AS value FROM test GROUP BY name; +----+------+-------+ | id | name | value | +----+------+-------+ |  1 | row1 |    10 | |  2 | row2 |     5 | +----+------+-------+ 2 rows in set (0.00 sec) 

Now, the id row2 is 2, but it should be 4.

I also tried with a join:

mysql> SELECT t1.* FROM         (SELECT id, name, MIN(value) AS value            FROM test GROUP BY name) AS t1         INNER JOIN test AS t2 ON t1.id = t2.id; +----+------+-------+ | id | name | value | +----+------+-------+ |  1 | row1 |    10 | |  2 | row2 |     5 | +----+------+-------+ 2 rows in set (0.00 sec) 

How can I get the correct ID for each result based on what the lowest value is?

like image 764
Pablo Fernandez heelhook Avatar asked Jun 04 '13 04:06

Pablo Fernandez heelhook


People also ask

How do you get a record with maximum value for each group?

MySQL MAX() function with GROUP BY retrieves maximum value of an expression which has undergone a grouping operation (usually based upon one column or a list of comma-separated columns).

Does GROUP BY reduce rows?

A GROUP BY normally reduces the number of rows returned by rolling them up and calculating averages or sums for each row. PARTITION BY does not affect the number of rows returned, but it changes how a window function's result is calculated.

Which row does GROUP BY return?

The GROUP BY clause groups a set of rows into a set of summary rows by values of columns or expressions. The GROUP BY clause returns one row for each group. In other words, it reduces the number of rows in the result set.

How do you find the first value in a GROUP BY?

First, you need to write a CTE in which you assign a number to each row within each group. To do that, you can use the ROW_NUMBER() function. In OVER() , you specify the groups into which the rows should be divided ( PARTITION BY ) and the order in which the numbers should be assigned to the rows ( ORDER BY ).


1 Answers

I think this is what you are trying to achieve:

SELECT t.* FROM test t JOIN  ( SELECT Name, MIN(Value) minVal   FROM test GROUP BY Name ) t2 ON t.Value = t2.minVal AND t.Name = t2.Name; 

Output:

ID VALUE NAME
1 10 row1
4 5 row2

See this SQLFiddle

  • Demo with more values
  • Demo with duplicate values
  • Demo with removing duplicate values (using DISTINCT)

Here I have self-joined the table with minVal and Name.

like image 155
Himanshu Jansari Avatar answered Sep 25 '22 01:09

Himanshu Jansari