user26480
user26480

Reputation: 387

SQL query on a time series to calculate the average

I have two tables:

temperature table which contains a time series of temperature taken every 15 minutes enter image description here

time table

enter image description here

I need a SQL query, which will allow for an average group by 15 minutes avry values taken for several days

can anyone help me please?

example: for 3 days

day1:00:00->10 ; 00:15->11 ;00:30->9......;23:45->12
day2:00:00->9 ; 00:15->2 ;00:30->5......;23:45->4
day3:00:00->8 ; 00:15->10 ;00:30->8......;23:45->5

how calculate:

avarage1 =10+9+8/3
avarage2 =11+2+10/3
avarage3=9+5+8/3
...
avarage96=12+4+5/3

help me please

Upvotes: 0

Views: 2421

Answers (2)

Erwin Brandstetter
Erwin Brandstetter

Reputation: 657882

If your test case is any indication of your real situation, your timestamps already fall on 15 minute intervals exactly and you don't need to trunc() at all. Just a plain GROUP BY / avg():

SELECT  date_time, avg(value) As avg_val
FROM    temperature te
JOIN    "time" ti USING (id_date)
WHERE   date_time >= '2015-02-24'::date
AND     date_time <  '2015-02-28'::date
GROUP   BY 1;

Selecting the time slice of 3 days from '2015-02-24'::date to '2015-02-27'::date. Note how I include the lower and exclude the upper bound.

Aside: don't use the reserved word "time" as identifier.

Upvotes: 1

Andomar
Andomar

Reputation: 238176

Create a group for each quarter, then use the avg() aggregate function to calculate the average temperature per group:

select  years
,       months
,       days
,       hours
,       floor(minutes / 15)
,       avg(value)
from    Temperature te
join    Time ti
on      te.id_date = ti.id
group by
        years
,       months
,       days
,       hours
,       floor(minutes / 15)

Or a more explicit alternative way to create a group per quarter:

group by
        years
,       months
,       days
,       hours
,       case
        when minutes < 15 then 1
        when minutes < 30 then 2
        when minutes < 45 then 3
        else 4
        end

Upvotes: 0

Related Questions