I need columns from a row based on the aggregate function.
if I have a list of activities for an id, can I get a list of the last activity for each id, listing the id, the last_date AND the corresponding activity
CREATE TABLE IF NOT EXISTS `activity_log` ( `activity_id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `id` int(255) NOT NULL, `date_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `user` varchar(35) NOT NULL, `activity` varchar(50) NOT NULL)
SELECT id, activity, max(activity_id) as ma FROM activity_log
group by id
returns the id and correctly the last date, but the activity is not the one that corresponds to the max(activity_id)
data example
id activity date_time
1 baseball 2011-8-1
1 football 2011-8-9
2 tennis 2011-7-3
2 hockey 2011-8-9
returns
1 baseball 2011-8-9 (I'd like to see football)
2 tennis 2011-8-9 (I'd like to see hockey)
thanks
Try something a little more like this:
The trick is to get the activity_id from the max of each group of records that share id in a sub-query, then join on those results to get the other columns of that specific record.