如何将时间段划分为部分?

时间:2017-06-08 08:51:14

标签: sql postgresql

表中有一列用于存储创建记录的时间。查询指定结束日期和开始日期,然后将间隔分为n个部分。在每个间隙中,我需要计算数据库中的记录数。 告诉我要添加到查询中的内容。此外,我需要计算记录的数量,即使它们当时不是。

F.e。

----------------------------
 id |      query date      |
----------------------------
1   | 2017-06-08 01:23:00  |
2   | 2017-06-08 01:24:19  |
3   | 2017-06-08 01:24:21  |
4   | 2017-06-08 01:24:36  |
5   | 2017-06-08 01:24:37  |
6   | 2017-06-08 01:24:41  |
----------------------------

我选择从2017-06-08 01:24:00到2017-06-08 01:26:00的时间段并将此期间分为4部分,然后我等待

------------------------------
 count |      query date      |
------------------------------
2      | 2017-06-08 01:24:00  |
3      | 2017-06-08 01:24:30  |
0      | 2017-06-08 01:25:00  |
0      | 2017-06-08 01:25:30  |
------------------------------

我的开始

select to_timestamp(extract(epoch from query_date)/extract(epoch FROM age('2017-06-08 01:25:00', '2017-06-08 01:24:00'))/60), count(*) from logs group by extract(epoch from query_date)/extract(epoch FROM age('2017-06-08 01:25:00', '2017-06-08 01:24:00'))/60;

1 个答案:

答案 0 :(得分:1)

尝试generate_series,如:

t=# with a as (
        with ali as (
                select g from generate_series('2017-06-08 01:24:00','2017-06-08 01:26:00','30 seconds'::interval) g
        )
        select g as t1, lead(g) over (order by g) t2
        from ali
        limit 4
)
select count(id), a.t1, coalesce(avg(id),0)
from a
left outer join logs l on l.query_date >= t1 and l.query_date <t2
group by a.t1
order by t1;
 count |           t1           |      coalesce
-------+------------------------+--------------------
     2 | 2017-06-08 01:24:00+00 | 2.5000000000000000
     3 | 2017-06-08 01:24:30+00 | 5.0000000000000000
     0 | 2017-06-08 01:25:00+00 |                  0
     0 | 2017-06-08 01:25:30+00 |                  0
(4 rows)

更新以通过OP通知重新构建 - 我使用coalesce来&#34;将默认值设置为零&#34;对于avg()返回NULL

的行