Postgres - 按间隔查询时间序列组

时间:2016-04-29 20:57:06

标签: sql postgresql grouping

我有一张桌子 - BusInfo,用于存储乘坐公共汽车的乘客数量以及他/她可以占用多少个座位(1个或多个,取决于他/她拥有的行李)。 我为它创造了一个小提琴 -

http://sqlfiddle.com/#!15/88226/11

start                        end                  bus_name  seats   start_time  ride_time
April, 28 2016 17:00:00 April, 28 2016 18:00:00   CA        2   1461862800      3600
April, 28 2016 17:30:00 April, 28 2016 18:30:00   CA        1   1461864600      3600
April, 28 2016 17:45:00 April, 28 2016 18:45:00   CA        2   1461865500      3600
April, 28 2016 17:00:00 April, 28 2016 19:00:00   CA        1   1461862800      7200
April, 28 2016 17:00:00 April, 28 2016 17:30:00   CA        2   1461862800      1800

我想运行一个查询,以10分钟的间隔获得座位占用率。这样的预期输出

datetime |  seats occupied at the time
17:00   5
17:10   5
17:20   5
17:30   4
17:40   4
17:50   6
18:00   4

我尝试过小组但没有接近 -

select to_char(to_timestamp(floor((extract('epoch' from to_timestamp(start_time))/ 600))*600),'yyyy/MM/dd HH24:MI'), 
              sum(seats) from businfo 

where start_time >= 1461862800 and start_time <= 1461866400 
and (start_time+ride_time) >= (1461862800)
group by to_char(to_timestamp(floor((extract('epoch' from     
to_timestamp(start_time))/ 600))*600),'yyyy/MM/dd HH24:MI')
order by to_char(to_timestamp(floor((extract('epoch' from   
      to_timestamp(start_time))/ 600))*600),'yyyy/MM/dd HH24:MI') ASC

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

一种方法使用generate_series()

select gs.ts, sum(seats)
from generate_series('2016-04-28 17:00:00'::timestamp, '2016-04-28 18:00:00', interval '10 minute') gs(ts) join
     businfo bi
     on gs.ts between bi.start and bi.end
group by gs.ts
order by gs.ts;