Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I SELECT rows with MAX(Column value), PARTITION by another column in MYSQL?

My table is:

id home datetime player resource
1 10 04/03/2009 john 399
2 11 04/03/2009 juliet 244
5 12 04/03/2009 borat 555
3 10 03/03/2009 john 300
4 11 03/03/2009 juliet 200
6 12 03/03/2009 borat 500
7 13 24/12/2008 borat 600
8 13 01/01/2009 borat 700

I need to select each distinct home holding the maximum value of datetime.

Result would be:

id home datetime player resource
1 10 04/03/2009 john 399
2 11 04/03/2009 juliet 244
5 12 04/03/2009 borat 555
8 13 01/01/2009 borat 700

I have tried:

-- 1 ..by the MySQL manual:   SELECT DISTINCT   home,   id,   datetime AS dt,   player,   resource FROM topten t1 WHERE datetime = (SELECT   MAX(t2.datetime) FROM topten t2 GROUP BY home) GROUP BY datetime ORDER BY datetime DESC 

Doesn't work. Result-set has 130 rows although database holds 187. Result includes some duplicates of home.

-- 2 ..join  SELECT   s1.id,   s1.home,   s1.datetime,   s1.player,   s1.resource FROM topten s1 JOIN (SELECT   id,   MAX(datetime) AS dt FROM topten GROUP BY id) AS s2   ON s1.id = s2.id ORDER BY datetime  

Nope. Gives all the records.

-- 3 ..something exotic:  

With various results.

like image 608
Kaptah Avatar asked Mar 04 '09 20:03

Kaptah


People also ask

How do I get the maximum value from another column of a table in SQL?

In SQL Server there are several ways to get the MIN or MAX of multiple columns including methods using UNPIVOT, UNION, CASE, etc… However, the simplest method is by using FROM … VALUES i.e. table value constructor. Let's see an example. In this example, there is a table for items with five columns for prices.

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.

Can we use MAX function in WHERE clause?

Overview. The MAX() function is used with the WHERE clause to gain further insights from our data. In SQL, the MAX() function computes the highest or maximum value of numeric values in a column.

How do I find the maximum value of a row in SQL?

To find the maximum value of a column, use the MAX() aggregate function; it takes a column name or an expression to find the maximum value. In our example, the subquery returns the highest number in the column grade (subquery: SELECT MAX(grade) FROM student ).


1 Answers

You are so close! All you need to do is select BOTH the home and its max date time, then join back to the topten table on BOTH fields:

SELECT tt.* FROM topten tt INNER JOIN     (SELECT home, MAX(datetime) AS MaxDateTime     FROM topten     GROUP BY home) groupedtt  ON tt.home = groupedtt.home  AND tt.datetime = groupedtt.MaxDateTime 
like image 100
Michael La Voie Avatar answered Sep 18 '22 13:09

Michael La Voie