Forum Moderators: coopster

Message Too Old, No Replies

MySQL GROUP BY and MAX problem

An issue with using GROUP BY and MAX together with 3 fields

         

gabrielmobius

5:12 pm on May 22, 2007 (gmt 0)

10+ Year Member



I'm having an issue with a MySQL query. The table I'm pulling from has 3 fields: UserID, Event and Timestamp. I use the statement

SELECT ID, Event, max(Time) as Time FROM log GROUP BY ID

to extract the information. It seems to work, as it extracts the most recent timestamp for each user ID. However, the Event displayed seems to be the Event that was first entered into the database. The current dataset looks like this:

ID ¦ Event ¦ Time
1 ¦ In ¦ 2007-05-22 12:07:26
3 ¦ In ¦ 2007-05-15 12:07:15
1 ¦ Out ¦ 2007-05-22 12:09:32
3 ¦ Out ¦ 2007-05-22 12:09:35
2 ¦ In ¦ 2007-05-22 12:43:43
2 ¦ Lunch ¦ 2007-05-22 12:43:52
4 ¦ Out ¦ 2007-05-22 12:47:20
4 ¦ In ¦ 2007-05-22 12:47:26

The output when I run that query is

ID ¦ Event ¦ Time
1 ¦ In ¦ 2007-05-22 12:09:32
2 ¦ In ¦ 2007-05-22 12:43:52
3 ¦ In ¦ 2007-05-22 12:09:35
4 ¦ Out ¦ 2007-05-22 12:47:26

Can anyone help me figure out exactly why it's doing this, or does anyone have any fixes? Thanks.

LifeinAsia

5:57 pm on May 22, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



Try:
SELECT ID, Event, max(Time) as Time
FROM log
GROUP BY ID, Event