2012-09-27 104 views
2

我有一個數據集,其中包含日期{yyyy/mm/dd}和時間{h,m,s}和溫度{float}作爲單個列。時間範圍聚合

我想通過平均函數來彙總每一天的溫度值。

的問題是,我不知道我怎麼可以查詢的時間屬性,例如總{h,m, (0-5)s}{h,m, (5-10)s}{h,m, (10-15)s}和...,自動說。

+0

看看這個:http://www.depesz.com/2010/10/22/grouping-data-into-time-ranges/ –

+0

據我所知應該包含數據和時間作爲一個相同的列使用上述方法。在我的數據集中,日期和時間分別放置在列中。 –

回答

1
select 
    day, 
    to_char(date_trunc('minute', "time"), 'HH24:MI') as "minute", 
    extract(second from "time")::integer/5 as "range", 
    avg(temperature) as average 
from (
    select d::date as day, d::time as "time", random() * 100 as temperature 
    from generate_series('2012-01-01', '2012-01-03', '1 second'::interval) s(d) 
) d 
group by 1, 2, 3 
order by 1, 2, 3 
; 

如果你想爲所有天數的平均:

select 
    to_char(date_trunc('minute', "time"), 'HH24:MI') as "minute", 
    extract(second from "time")::integer/5 as "range", 
    avg(temperature) as average 
from (
    select d::time as "time", random() * 100 as temperature 
    from generate_series('2012-01-01', '2012-01-03', '1 second'::interval) s(d) 
) d 
group by 1, 2 
order by 1, 2 
; 

我覺得你的問題的重要組成部分,是一羣以秒的範圍大小劃分的整數結果。

+0

親愛的Clodoaldo,爲了使用上述代碼,我應該在單個列中有時間和日期嗎? –

+0

@aliamidi它既可以是單列也可以是兩列。上面的generate_series生成一個列。您的查詢將不使用generate_series,而是使用您自己的表。 –