开发者

MYSQL - How to get non aggregate columns from a table based on an aggregate column

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)开发者_Python百科

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:

Select al.id, al.activity, al.activity_id
From activty_log
Join (Select max(aa.activity_id) as ma From activity_log aa group by aa.id) As al2
 On al2.ma = al2.activity_id;

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.


SELECT id, activity, activity_id as ma FROM activity_log s where not exists (select id from activity_log where id = s.id and s.activity_id < activity_id );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜