Skip to content
Advertisement

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

I have a table of player performance:

What query will return the rows for each distinct home holding its maximum value of datetime? In other words, how can I filter by the maximum datetime (grouped by home) and still include other non-grouped, non-aggregate columns (such as player) in the result?

For this sample data:

the result should 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 tried a subquery getting the maximum datetime for each home:

The result-set has 130 rows although database holds 187, indicating the result includes some duplicates of home.

Then I tried joining to a subquery that gets the maximum datetime for each row id:

Nope. Gives all the records.

I tried various exotic queries, each with various results, but nothing that got me any closer to solving this problem.

Advertisement

Answer

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:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement