从 TimescaleDB 获取 1 年的结果

Get 1 Year results from TimescaleDB

我有一个 table,其中包含物联网设备的数据,每小时发送一次测量值。必须获取今天、周、月和年的报告。

使用 timescaleDB 我得到了今天、周和月的一些 "ok" 结果。例如每月:

   SELECT
      time_bucket('4 weeks', measured_at) AS month,
      MAX(CAST(data->>'1_8_0' AS DOUBLE PRECISION)) - MIN(CAST(data->>'1_8_0' AS DOUBLE PRECISION)) as consumption
      FROM readings
      WHERE device_id = 4
      GROUP BY month
      ORDER BY month DESC LIMIT 12;

但是多年来一直找不到好的取值方法?有人试过吗?

时间刻度不支持年,使用周会导致错误结果。

错误:不支持按月、年、世纪等定义的间隔

暂时time_bucket不支持month/year:见#414

time_bucket is designed for regular intervals like days, hours, minutes. As months and years are variable time units, the function does not support them

postgres date_trunc 也支持 month/year

请确保您知道您实际汇总了哪些数据time_bucket

TIMESTAMPTZ arguments are bucketed by the time at UTC. So the alignment of buckets is on UTC time. One consequence of this is that daily buckets are aligned to midnight UTC, not local time.

正如@TmTron 已经指出的,几个月和几年的实际正确版本将使用 date_trunc,如下所示:

SELECT
    date_trunc('month', measured_at) AS month,
    MAX(CAST(data->>'1_8_0' AS DOUBLE PRECISION)) - MIN(CAST(data->>'1_8_0' AS DOUBLE PRECISION)) as consumption
    FROM readings
    WHERE device_id = 4
    GROUP BY 1
    ORDER BY 1 DESC LIMIT 12;

...和:

SELECT
    date_trunc('year', measured_at) AS year,
    MAX(CAST(data->>'1_8_0' AS DOUBLE PRECISION)) - MIN(CAST(data->>'1_8_0' AS DOUBLE PRECISION)) as consumption
    FROM readings
    WHERE device_id = 4
    GROUP BY 1
    ORDER BY 1 DESC LIMIT ...;

并且如果您只 select 特定时间间隔(例如过去 12 个月),请始终 添加条件以减少要扫描的分区数量,例如:

SELECT
    date_trunc('month', measured_at) AS month,
    MAX(CAST(data->>'1_8_0' AS DOUBLE PRECISION)) - MIN(CAST(data->>'1_8_0' AS DOUBLE PRECISION)) as consumption
    FROM readings
    WHERE device_id = 4
        AND measured_at >= CURRENT_TIMESTAMP - '13 months'::interval
    GROUP BY 1
    ORDER BY 1 DESC LIMIT 12;