10

I have a table with timestamp field and usage field like this

            timestamp  | usage
'2015-06-13 13:45:58'  | 240
'2015-06-13 13:45:59'  | 480
'2015-06-13 13:46:00'  | 240
'2015-06-13 13:46:01'  | 320
 ...

I want to get sum of usage for a period of '1 week' with '30 minutes' interval. I can get data only for intervals in minute, hour, day and ...

SELECT date_trunc('minute', timestamp) as clock, sum(usage)
FROM my_table
WHERE timestamp > localtimestamp - INTERVAL '1 week'
GROUP BY clock

how to get data for intervals like '5 minutes', '30 minutes', '2 days' and ... .

4
  • If I get you right - you want to sum(usage) over a field that is between date_trunc('minute', timestamp) and date_trunc('minute', timestamp) + '30 minutes'::interval as a subquery, and then the upper one?.. right?.. Commented Jun 18, 2015 at 8:23
  • I think that's right. I want each result's row show usage of 30 minutes. Commented Jun 18, 2015 at 8:29
  • does the below query work for you?.. Commented Jun 18, 2015 at 8:36
  • @VaoTsun do you have another suggestion? Commented Jun 20, 2015 at 5:27

1 Answer 1

12

Use the following to get what your after.

SELECT TIMESTAMP WITH TIME ZONE 'epoch' + INTERVAL '1 second' * round((extract('epoch' FROM timestamp) / 1800) * 1800) AS clock,  SUM(usage)
FROM my_table 
WHERE timestamp > localtimestamp - INTERVAL '1 week'
GROUP BY round(extract('epoch' FROM timestamp) / 1800)
Sign up to request clarification or add additional context in comments.

5 Comments

return error in line 1: "column "timestamp" must appear in the GROUP BY clause or be used in an aggregate function"
it is in the group by, did you copy all the code, or did you add to it?
I use pgadmin to test this query and it draws error line under 'timestamp' in this section on line one! "round((extract('epoch' FROM timestamp)" . and about changes, I change 'timestamp' to 'time_stamp' and 'my_table' to 'records', just this!
I test this code without any change again. but the error is still. I change group by section to 'group by clock', but query return all of records.
Finally, I found problem :). you should bring out second 1800 from 'round' function and group by 'clock'. please update your answer, I want check it as a correct answer. thank you.

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.