gpt4 book ai didi

PostgreSQL 动态 date_trunc 函数四舍五入到给定的时间戳

转载 作者:行者123 更新时间:2023-11-29 13:11:31 25 4
gpt4 key购买 nike

我正在使用内置的 PostgreSQL 函数 date_trunc() 来聚合时间窗口,如下所示:

SELECT max(time) as time, 
COUNT(*) as ticks
FROM sensorticks
WHERE time between (TIMESTAMP'2019-01-04 00:15:00') AND (TIMESTAMP'2019-01-04 14:15:00')
GROUP BY date_trunc('hour', time)
ORDER BY time desc;

结果是这样的:

time                        ticks
2019-01-04 14:14:59 892
2019-01-04 13:59:59 3575
2019-01-04 12:59:59 3552
2019-01-04 11:59:59 3560
2019-01-04 10:59:59 2671

但我不想切断第一个窗口。我需要从 14:15 开始的动态时间窗口(14:15、13:15 等等)。它应该看起来像这样:

time                        ticks
2019-01-04 14:14:59 3575
2019-01-04 13:14:59 3575
2019-01-04 12:14:59 3552
2019-01-04 11:14:59 3560
2019-01-04 10:14:59 3575

我该怎么做?

最佳答案

您查询的时间窗口似乎取决于 WHERE 子句中出现的上限范围。由于现在是整点 15 分钟,您可以尝试将时间向前移动 45 分钟进行汇总:

SELECT
MAX(time) AS time,
COUNT(*) AS ticks
FROM sensorticks
WHERE time BETWEEN (TIMESTAMP'2019-01-04 00:15:00') AND (TIMESTAMP'2019-01-04 14:15:00')
GROUP BY date_trunc('hour', time + interval '45 minutes')
ORDER BY time DESC;

但是上面的查询还是有问题,因为显示的时间还是有可能不正确。此外,某些时间段可能会丢失,但您仍然可能想要报告它们。要解决这个问题,我们可以尝试使用日历表:

WITH calendar AS (
SELECT TIMESTAMP '2019-01-04 14:00:00' AS ts, TIMESTAMP '2019-01-04 14:14:59' AS display UNION ALL
SELECT TIMESTAMP '2019-01-04 13:00:00', TIMESTAMP '2019-01-04 13:14:59' UNION ALL
SELECT TIMESTAMP '2019-01-04 12:00:00', TIMESTAMP '2019-01-04 12:14:59' UNION ALL
SELECT TIMESTAMP '2019-01-04 11:00:00', TIMESTAMP '2019-01-04 11:14:59' UNION ALL
SELECT TIMESTAMP '2019-01-04 10:00:00', TIMESTAMP '2019-01-04 10:14:59'
)

然后,我们可以使用原始查询连接到这个日历表:

SELECT
c.display AS time,
COUNT(*) AS ticks
FROM calendar c
LEFT JOIN sensorticks s
ON c.ts = date_trunc('hour', s.time + interval '45 minutes')
WHERE s.time BETWEEN (TIMESTAMP'2019-01-04 00:15:00') AND (TIMESTAMP'2019-01-04 14:15:00')
GROUP BY c.display
ORDER BY c.display DESC;

关于PostgreSQL 动态 date_trunc 函数四舍五入到给定的时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54040594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com