Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

date_trunc 5 minute interval in PostgreSQL [duplicate]

Possible Duplicate:
What is the fastest way to truncate timestamps to 5 minutes in Postgres?
Postgresql SQL GROUP BY time interval with arbitrary accuracy (down to milli seconds)

I want to aggregate data at 5 minute intervals in PostgreSQL. If I use the date_trunc() function, I can aggregate data at an hourly, monthly, daily, weekly, etc. interval but not a specific interval like 5 minute or 5 days.

select date_trunc('hour', date1), count(*) from table1 group by 1; 

How can we achieve this in PostgreSQL?

like image 682
prateekk Avatar asked Aug 28 '12 19:08

prateekk


People also ask

How do I create an interval in PostgreSQL?

In PostgreSQL, the make_interval() function creates an interval from years, months, weeks, days, hours, minutes and seconds fields. You provide the years, months, weeks, days, hours, minutes and/or seconds fields, and it will return an interval in the interval data type.

What is Date_trunc in PostgreSQL?

In PostgreSQL, DATE_TRUNC Function is used to truncate a timestamp type or interval type with specific and high level of precision. Syntax: date_trunc('datepart', field) The datepart argument in the above syntax is used to truncate one of the field,below listed field type: millennium. century.

Is interval data type in PostgreSQL?

In PostgreSQL the interval data type is used to store and manipulate a time period. It holds 16 bytes of space and ranging from -178, 000, 000 years to 178, 000, 000 years.


1 Answers

SELECT date_trunc('hour', date1) AS hour_stump      , (extract(minute FROM date1)::int / 5) AS min5_slot      , count(*) FROM   table1 GROUP  BY 1, 2 ORDER  BY 1, 2; 

You could GROUP BY two columns: a timestamp truncated to the hour and a 5-minute-slot.

The example produces slots 0 - 11. Add 1 if you prefer 1 - 12.
I cast the result of extract() to integer, so the division / 5 truncates fractional digits. The result:
minute 0 - 4 -> slot 0
minute 5 - 9 -> slot 1
etc.

This query only returns values for those 5-minute slots where values are found. If you want a value for every slot or if you want a running sum over 5-minute slots, consider this related answer:

  • PostgreSQL: running count of rows for a query 'by minute'
like image 67
Erwin Brandstetter Avatar answered Sep 24 '22 16:09

Erwin Brandstetter