如何根据设备ID select 某些设备发送的最后一条消息?

How to select last message send by some devices according to the device ID?

我的 postgreSql 数据库中有一条消息 table。 table 的名称为:deviceId、timestamp、message。 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台设备,每台设备在不同的时间发送了很多消息。我想 select 某些设备发送的最后一条消息。例如,dev12345dev22245 发送的最后一条消息:hello Jackhello 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