我的PostgreSQL数据库中有一个消息表。该表具有名称:deviceId,timestamp,消息。deviceId相同,表示现有设备的ID。
deviceId timestamp message
dev12345 2020-01-02 21:01:02 hello Jack
dev12229 2020-01-02 12:03:02 good
dev22245 2020-01-01 12:01:05 hello Mary
dev12345 2020-01-01 11:03:02 good morning
... ... ...
假设总共有100台设备,每个设备在不同时间发送了许多消息。我想选择某些设备发送的最后一条消息。例如,dev12345
和dev22245
发送的最后一条消息:hello Jack
和hello Mary
您能告诉我如何使用postgreSql命令吗?
谢谢
在Postgres中,只需使用distinct on
:
select distinct on (deviceId) t.*
from mytable t
where device id in ('dev12345', 'dev22245')
order by deviceId, timestamp desc
distinct on (deviceId)
子句指示数据库,我们只希望每个设备一个记录; order by
子句控制在每个组中保留哪一行(此处,排序将优先级分配给每个设备的最新记录)。
您可以使用Windows函数(row_number)和CTE组合:
WITH sub as (
select deviceId,message ,row_number() OVER (partition by deviceId order by ts desc) as num FROM tab )
SELECT deviceId,message FROM sub where num= 1