Select查询以4小时为间隔取数据

Select query for fetching data on the interval of 4 hours

我正在使用 postgres 8.1 数据库,我想编写一个查询,其中 select 数据间隔为 4 小时。

所以图片显示 subscriber_id 和日期,这是数据库中当前可用数据的方式

我想要

这样的数据
No. of Subscriber |  Interval
      0               0-4
      0               4-8
      7               8-12
      1               12-16
      0               16-20
      0               20-24

基本上每天我们有 24 小时,如果我除以 24/4=6 意味着我每天总共有 6 个间隔

0-4
4-8
8-12
12-16
16-20
20-24

所以我需要这些时间间隔内的订阅者数量。 postgres 中是否有任何数据函数可以解决我的问题,或者我该如何为这个问题编写查询?

注意:请根据postgres 8.1版本编写解决方案

在 Postgres 中,您可以通过为您的时间段生成所有间隔来完成此操作。这有点棘手,因为您必须在数据中挑选日期。但是,generate_series() 确实很有帮助。

剩下的只是一个left join和聚合:

select dt.dt, count(t.t)
from (select generate_series(min(d.dte), max(d.dte) + interval '23 hour', interval '4 hour') as dt
      from (select distinct date_trunc('day', t.t)::date as dte from t) d 
     ) dt left join
     t
    on t.t >= dt.dt and t.t < dt.dt + interval '4 hour'
group by dt.dt
order by dt.dt;

请注意,这会将句点保留为句点开头的 date/time。如果更有帮助,您可以轻松地将其转换为日期和间隔数字。

我想如果你 运行 六个不同的查询,因为你知道时间间隔(下限和上限)会更好。

使用 generate_series() 生成句点并使用适当的句点左连接 date_time,例如:

with my_table(date_time) as (
values
('2016-10-24 11:10:00'::timestamp),
('2016-10-24 11:20:00'),
('2016-10-24 15:10:00'),
('2016-10-24 21:10:00')
)

select 
    format('%s-%s', p, p+4) as "interval", 
    sum((date_time notnull)::int) as "no of subscriber"
from generate_series(0, 20, 4) p
left join my_table
on extract(hour from date_time) between p and p+ 4
group by p
order by p;

 interval | no of subscriber 
----------+------------------
 0-4      |                0
 4-8      |                0
 8-12     |                2
 12-16    |                1
 16-20    |                0
 20-24    |                1
(6 rows)    

我不认为会有人记得 8.1 版。你可以试试:

create table periods(p integer);
insert into periods values (0),(4),(8),(12),(16),(20);

select 
    p as "from", p+4 as "to", 
    sum((date_time notnull)::int) as "no of subscriber"
from periods
left join my_table
on extract(hour from date_time) between p and p+ 4
group by p
order by p;

 from | to | no of subscriber 
------+----+------------------
    0 |  4 |                0
    4 |  8 |                0
    8 | 12 |                2
   12 | 16 |                1
   16 | 20 |                0
   20 | 24 |                1
(6 rows)