How do you get the rows that contain the max value for each grouped set?
I've seen some overly-complicated variations on this question, and none with a good answer. I've tried to put together the simplest possible example:
Given a table like that below, with person, group, and age columns, how would you get the oldest person in each group? (A tie within a group should give the first alphabetical result)
Person | Group | Age
---
Bob | 1 | 32
Jill | 1 | 34
Shawn| 1 | 42
Jake | 2 | 29
Paul | 2 | 36
Laura| 2 | 39
Desired result set:
Shawn | 1 | 42
Laura | 2 | 39
You can also try
Using ranking method.
I would not use Group as column name since it is reserved word. However following SQL would work.
I have a simple solution by using
WHERE IN
You can join against a subquery that pulls the
MAX(Group)
andAge
. This method is portable across most RDBMS.Not sure if MySQL has row_number function. If so you can use it to get the desired result. On SQL Server you can do something similar to: