如果您有一些最新的活动,例如
user_id created_at id
john july 4, 2010 1
john july 4, 2010 2
john july 12, 2010 3 -- ties with id# 4
john july 12, 2010 4 -- ties with id# 3
john july 5, 2010 5
paul july 13, 2010 6
paul july 12, 2010 7
使用dense_rank:
with latest_activities as
(
SELECT user_id, created_at, id,
dense_rank()
over(partition by user_id order by created_at desc) as the_ranking
FROM activities
)
select *
from latest_activities
where the_ranking = 1
order by user_id, id;
上面的查询将显示:
user_id created_at id
john july 12, 2010 3
john july 12, 2010 4
paul july 13, 2010 6
如果您希望每个用户的多个 id 仅出现在一行上,请使用group_concat array_agg,它将显示以下内容:
user_id created_at ids
john july 12, 2010 3, 4
paul july 13, 2010 6
数组聚合:
with latest_activities as
(
SELECT user_id, created_at, id,
dense_rank()
over(partition by user_id order by created_at desc) as the_ranking
FROM activities
)
select user_id, created_at, array_agg(id order by id) as ids
from latest_activities
where the_ranking = 1
group by user_id, created_at
请注意,上面的查询也在处理没有关联的数据
现场测试:http ://www.sqlfiddle.com/#!12/c48ec/8