根据多个 id 获取最新出现的行

Fetch the row which has the latest occurrence based on multiple ids

我正在尝试查找每个用户每个会话的最后一条消息。每个消息行都有用户 ID 和它是哪个用户会话(每个会话递增 1)

我的 table 看起来像这样:

user_id | timestamp                  | usermessage   | user_session_id

1       | 2019-08-28 14:50:39.150000 | hi            | 1
1       | 2019-08-28 14:50:40.150000 | goodbye       | 1
1       | 2019-09-01 10:50:39.150000 | hello again   | 2
1       | 2019-09-01 11:50:39.150000 | goodbye again | 2
2       | 2019-07-09 07:53:56.680000 | hello         | 1 
2       | 2019-07-10 09:23:16.100000 | hi there      | 2     

我想检索每个用户在每个会话中发布的最后一条消息(最新时间戳)。所以我的预期输出是这样的

user_id | timestamp                  | usermessage   | user_session_id
1       | 2019-08-28 14:50:40.150000 | goodbye       | 1
1       | 2019-09-01 11:50:39.150000 | goodbye again | 2
2       | 2019-07-09 07:53:56.680000 | hello         | 1 
2       | 2019-07-10 09:23:16.100000 | hi there      | 2       

提前致谢

使用row_number()

select * from     
(select *,row_number() over(partition by user_id, user_session_id order by timestamp desc) rn
from table_name
) a where a.rn=1

在 Postgres 中,我会推荐 distinct on:

select distinct on (user_id, user_session_id) t.*
from t
order by user_id, user_session_id, timestamp desc;

在 Postgres 中,这通常是执行此类查询的最有效方法。为了获得最佳性能,您需要在 (user_id, user_session_id, timestamp desc).

上建立索引