【问题标题】:How to select last message send by some devices according to the device ID? [duplicate]如何根据设备ID选择某些设备发送的最后一条消息? [复制]
【发布时间】:2020-06-15 07:44:09
【问题描述】:

我的 postgreSql 数据库中有一个消息表。该表具有名称: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 个设备,每个设备在不同的时间发送了许多消息。我想选择某些设备发送的最后一条消息。例如dev12345dev22245最后发送的消息:hello Jackhello Mary

你能告诉我如何使用 postgreSql 命令来做到这一点吗?

谢谢

【问题讨论】:

标签: sql postgresql date greatest-n-per-group


【解决方案1】:

在 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 子句控制在每个组中保留哪一行(在这里,排序优先于每个设备的最新记录)。

【讨论】:

    【解决方案2】:

    你可以使用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  
    

    【讨论】:

      猜你喜欢
      • 2014-05-19
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-10
      • 2020-11-22
      相关资源
      最近更新 更多