在以下数据库中,
id userid eventid created_at
1 1 100 2010-01-01
2 1 101 2010-02-01
3 1 100 2010-03-01
4 1 101 2010-04-01
5 2 100 2010-05-01
6 2 100 2010-06-01
我正在尝试基于eventid获取每个用户的最新活动,并给出如下输出:
6 2 100 2010-06-01
4 1 101 2010-04-01
3 1 100 2010-03-01
答案 0 :(得分:4)
使用group by
和aggregation
select userid,envid,max(id) as id, max(created_at) as created_at
from tablename a
group by userid,envid
答案 1 :(得分:3)
使用行数
SELECT *
FROM (SELECT ROW_NUMBER() OVER (PARTITION BY userid, eventid ORDER BY id DESC) as RId,
t.*
FROM Tablename t
) T
WHERE RId = 1 ;