请确保您知道您实际汇总了哪些数据time_bucket
:
TIMESTAMPTZ 参数按 UTC 时间存储。所以桶的对齐是在UTC时间。这样做的一个结果是,每日存储桶与午夜 UTC 对齐,而不是本地时间。
正如@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 ...;
如果您只选择某个时间间隔(例如过去 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;