Aggregation on time range

大城市里の小女人 提交于 2019-12-23 17:02:52

问题


I have a data-set that contains date {yyyy/mm/dd} and time {h,m,s} and temperature {float} as an individual columns.

I want to aggregate temperature values for each day by average function.

The problem is that, I don't know how I can query the time attribute to say for example aggregate {h,m, (0-5)s} and {h,m, (5-10)s} and {h,m, (10-15)s} and ..., automatically.


回答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
;

If you want the average for all days:

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
;

I think the important part for your question is to group by the integer result of the division of the seconds by the range size.



来源:https://stackoverflow.com/questions/12615969/aggregation-on-time-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!