2016-04-29 96 views
0

我有一個表格BusInfo,它存儲了乘客上車的人數以及他/她可以佔據多少個座位(取決於他/她擁有的行李數)。 我創建了一個搗鼓IT-Postgres - 按時間間隔查詢時間序列組

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分鐘interval.Something這樣得到座位佔用是預期的輸出

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 

有什麼想法?

回答

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; 
+0

感謝您的答覆。查詢返回了預期的結果,但儘管事實上我沒有一個非常大的數據庫,但它仍然很慢。我如何優化它?可能從添加索引開始。 – Harpreet

+0

我能否建議你提出另一個問題,明確表示性能? –