1

I have a table like this:

10/10/2018 00:00 | 5
10/10/2018 00:10 | 7
10/10/2018 00:20 | 9
...
10/10/2018 23:40 | 5
10/10/2018 23:50 | 6

I need to get average number in hour, and return all hour averages (from 00:00 to 23:00)

I can get two hour averages like this:

(select avg(value)
from public.table
where time_stamp between TO_TIMESTAMP('2018-11-05 20:00:00', 'YYYY-MM-DD HH24:MI:SS') 
and
TO_TIMESTAMP('2018-11-05 20:00:00', 'YYYY-MM-DD HH24:MI:SS') + interval '1 hour')
UNION ALL
(select avg(value)
from public.table
where time_stamp between TO_TIMESTAMP('2018-11-05 21:00:00', 'YYYY-MM-DD HH24:MI:SS') 
and
TO_TIMESTAMP('2018-11-05 21:00:00', 'YYYY-MM-DD HH24:MI:SS') + interval '1 hour')

But how can I got all 24 average values in some loop? I dont want to copy this SQL 24 times.

8
  • You might try truncating the timestamp down to the hour, then grouping your results by that truncated timestamp? Commented Nov 5, 2018 at 21:23
  • Not really understand how it need to work (my english skills are bad), can you give simple example? Commented Nov 5, 2018 at 21:24
  • Something like this: select date_trunc('hour', time_stamp), avg(value) from public.table where date_trunc('day', time_stamp) = date_trunc('day', TO_TIMESTAMP('2018-11-05 00:00:00', 'YYYY-MM-DD HH24:MI:SS')) group by date_trunc('hour', time_stamp); Commented Nov 5, 2018 at 21:26
  • I don't have a postgres machine available to test this on right now, but do a very similar thing in Oracle. Commented Nov 5, 2018 at 21:27
  • This script returns values of only first hour of day, but I need for all hours of day (total 24) Commented Nov 5, 2018 at 21:38

1 Answer 1

2

Give this a try

select 
   date_trunc('hour', time_stamp), avg(value) 
from 
   public.table 
where 
   date_trunc('day', time_stamp) = date_trunc('day', TO_TIMESTAMP('2018-11-05 00:00:00', 'YYYY-MM-DD HH24:MI:SS')) 
group by 
   date_trunc('hour', time_stamp);

The idea is to make all the timestamps only specific down to the hour. Then select all the records that appear on that day, grouped by hour. Perform your avg over the values within each hour grouping.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.