Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Group By Issue

Tags:

sql

SELECT SomeId, ModifiedUser, MAX(ModifiedDate) 
FROM SomeTable 
GROUP BY SomeId, ModifiedUser

Then I get results like this:

1000    User1    Mar 30 2011
1000    User2    Jun 25 2011
1001    User3    Mar 21 2011
1001    User4    Jun 20 2011

How do I modify the query so I get only

1000    User2    Jun 25 2011
1001    User4    Jun 20 2011

Basically take the first query results then group by SomeId with latest ModifiedDate and ModifiedUser connected to the latest ModifiedDate

like image 893
Connection Avatar asked Dec 16 '25 20:12

Connection


1 Answers

You have to do 2 queries and join them.

1st query:

SELECT SomeId, Max(ModifiedDate) 
FROM SomeTable GROUP BY SomeId

This singles out the "unique information". Then, you join that with:

SELECT SomeId, ModifiedUser, ModifiedDate 
from SomeTable 

to give you all the data. So, the complete query is:

SELECT SomeId, ModifiedUser, ModifiedDate 
FROM SomeTable 
INNER JOIN (
            SELECT SomeId, Max(ModifiedDate) maxmod 
            FROM SomeTable 
            GROUP BY SomeId) uniqueinfo ON SomeTable.SomeId = uniqueinfo.SomeId 
                                       AND ModifiedDate = uniqueinfo.maxmod
like image 86
Tim Almond Avatar answered Dec 19 '25 08:12

Tim Almond



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!