Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select distinct rows whilst grouping by max value

I currently have the following table:

ID   |  Name    |  EventTime            |  State
1001 |  User 1  |  2013/07/22 00:00:05  |  15
1002 |  User 2  |  2013/07/23 00:10:00  |  100
1003 |  User 3  |  2013/07/23 06:15:31  |  35
1001 |  User 1  |  2013/07/23 07:13:00  |  21
1001 |  User 1  |  2013/07/23 08:15:00  |  25
1003 |  User 3  |  2013/07/23 10:00:00  |  22
1002 |  User 2  |  2013/07/23 09:18:21  |  50

What I need is the state for each distinct userid from the last eventtime similar to below:

ID   |  Name    |  EventTime            |  State
1001 |  User 1  |  2013/07/23 08:15:00  |  25
1003 |  User 3  |  2013/07/23 10:00:00  |  22
1002 |  User 2  |  2013/07/23 09:18:21  |  50

I need something similar to the following but I can't quite get what I need.

SELECT ID, Name, max(EventTime), State
FROM MyTable
GROUP BY ID
like image 740
lethalMango Avatar asked Jul 23 '13 15:07

lethalMango


1 Answers

SELECT
ID, Name, EventTime, State
FROM
MyTable mt
WHERE EventTime = (SELECT MAX(EventTime) FROM MyTable sq WHERE mt.ID = sq.ID)
like image 77
fancyPants Avatar answered Nov 04 '22 04:11

fancyPants