基于多个ID提取最近出现的行

问题描述 投票:0回答:2

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

我的桌子看起来像这样:

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       

提前谢谢您

sql postgresql postgresql-9.6
2个回答
0
投票

使用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

0
投票

在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)上建立索引。

© www.soinside.com 2019 - 2024. All rights reserved.