按日期范围分组结果

时间:2019-04-05 01:09:50

标签: postgresql date group-by timestamp range

我在PostgreSQL中有一个带有timestamp列的表,需要统计24小时间隔的交互。样本数据:

CREATED
-----------------
2019-04-03 17:20:50
2019-04-03 17:20:59
2019-04-03 18:41:18
2019-04-04 09:58:49
2019-04-04 09:58:53
2019-04-04 09:58:59
2019-04-04 10:01:55
2019-04-04 14:52:52
2019-04-04 15:10:43
2019-04-04 15:10:53
2019-04-04 17:15:39

预期结果:

MIN(CREATED)            MAX(CREATED)          TOTAL
2019-04-03 17:20:50     2019-04-04 17:15:39   11

我目前有这个脚本,可以将日期转换为秒,但得到以下信息:

SELECT
    TIMESTAMP WITH TIME ZONE 'epoch' +
    INTERVAL '1 second' * trunc(extract('epoch' from created) / 86400) * 86400 as filtro,
    min(created),
    max(created),
    count(*)
FROM whts
GROUP BY filtro
ORDER BY max(created) desc;

FILTRO                      MIN(CREATED)                MAX(CREATED)                TOTAL
2019-04-04 00:00:00.000000  2019-04-04 09:58:49.000000  2019-04-04 17:15:39.000000  8
2019-04-03 00:00:00.000000  2019-04-03 17:20:50.000000  2019-04-03 18:41:18.000000  3

它应该返回一行,因为第一个created是: 2019-04-03 17:20:50 和最后一个 2019-04-04 17:15 :39 。没有 24小时

2 个答案:

答案 0 :(得分:2)

SELECT min(created)
     , max(created)
     , count(*)
FROM   whts
GROUP  BY date_trunc('day', created - time '17:20:50')  -- time of the start
ORDER  BY max(created) DESC;

基本技巧是扣除开始时间的时间成分(将值调整为适合每日网格的时间),然后您可以使用date_trunc()来组成组。

识别偏移量的最佳方法取决于任务的缺少定义...在哪里开始或结束此任务?

仅从表中最早的created开始:

SELECT min(created)
     , max(created)
     , count(*)
FROM   whts, (SELECT min(created)::time FROM whts) t(t_start)
GROUP  BY date_trunc('day', created - t.t_start) 
ORDER  BY max(created) DESC;

答案 1 :(得分:0)

不能将trunc函数用作所需结果的函数。 也许您可以尝试以下操作:     trunc((从(created-(从whts中选择min(created))中提取('epoch'))/ 86400)* 86400