Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bin timestamp data into buckets of n minutes in postgres

Tags:

postgresql

I have the following query which works, binning timestamped "observations" into buckets whose boundaries are defined by the bins table:

SELECT
  count(id),
  width_bucket(
      time :: TIMESTAMP,
      (SELECT ARRAY(SELECT start_time
                    FROM bins
                    WHERE owner_id = 'some id'
                    ORDER BY start_time ASC) :: TIMESTAMP[])
  ) bucket
FROM observations
WHERE owner_id = 'some id'
GROUP BY bucket
ORDER BY bucket;

I would like to modify this to allow for querying arbitrary n-minute bins starting from a specified timestamp, rather than having to pull from from an actual "bins" table.

That is, given a start time, a "bin width" in minutes, and a number of bins, is there a way I can generate the array of timestamps to pass into the width_bucket function?

Alternatively, is there a different/simpler approach to get the same results?

like image 803
AwesomeTown Avatar asked Nov 01 '25 13:11

AwesomeTown


1 Answers

Use the function generate_series(start, stop, step interval), e.g.

select array(
    select generate_series(
        timestamp '2018-04-15 00:00', 
        '2018-04-15 01:00', 
        '30 minutes'))

                               array                                
---------------------------------------------------------------------
 {"2018-04-15 00:00:00","2018-04-15 00:30:00","2018-04-15 01:00:00"}
(1 row)

Example in Db<>fiddle.

like image 74
klin Avatar answered Nov 04 '25 03:11

klin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!