我需要基于聚合函数的行中的列。
如果我有一个id的活动列表,我可以获得每个id的最后一个活动的列表,列出id,last_date和相应的活动
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
按ID分组
返回id并正确返回最后一个日期,但活动不是与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)
感谢
答案 0 :(得分:2)
尝试一下这样的事情:
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;
诀窍是从子查询中共享 id 的每组记录的最大值中获取 activity_id ,然后加入这些结果以获取另一个该特定记录的列。
答案 1 :(得分:1)
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 );