Select 在 postgres 中每分钟组一条记录

Select one record per minute group in postgres

我在 postgres 数据库中有一个很大的 table,其中包含单位位置。现在我需要每 60 秒检索一次位置。

在Mysql,这是小菜一碟:select * from location_table where unit_id = '123' GROUP BY round(timestamp / 60)

但在 postgres 中这似乎是一个非常困难的问题。我还有日期格式而不是纪元格式的时间戳。

这是 table 外观的示例

CREATE TABLE location_table (
    unit_id int,
    "timestamp" timestamp(3) without time zone NOT NULL,
    lat double precision,
    lng double precision
);

使用 date_trunc() 每分钟做一组:

SELECT  * -- most likely not what you want
FROM    location_table 
WHERE   unit_id = 123 -- numbers don't need quotes ' 
GROUP BY date_trunc('minute', 'timestamp');

*当然是错误的,但我不知道你想知道关于 GROUP 的什么,所以我想不出更好的东西。

编辑: 当您需要 table 的随机结果时,DISTINCT ON () 可以完成这项工作:

SELECT  DISTINCT ON(date_trunc('minute', timestamp))
     * -- your columns
FROM    location_table;

还有其他(标准 SQL)解决方案,例如使用 row_number()。