Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

group by 15-minute interval in PostgreSQL

here’s a sample from my table in Metabase PostgreSQL:

timestamp
2023-01-25T05:00:01+03:00
2023-01-25T05:01:01+03:00
2023-01-25T05:05:01+03:00
2023-01-25T05:13:01+03:00
2023-01-25T05:14:01+03:00
2023-01-25T05:20:01+03:00
2023-01-25T05:24:01+03:00
2023-01-25T05:29:01+03:00

I want to group by 15-minute interval and count events that happen in the interval:

timestamp            count
2023-01-25T05:00     5
2023-01-25T05:15     3     

this didn’t work

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT date_trunc('hour', timestamp_column) + (floor(date_part('minute', timestamp_column) / 15) * interval '15 minute') AS interval_start,
       COUNT(*)
FROM my_table
GROUP BY interval_start

and raised an error:

   Code: 46. DB::Exception: Unknown function date_part: While processing dateTrunc('hour', timestamp) + (floor(date_part('minute', timestamp) / 15) * toIntervalMinute(15)) AS interval_start. 
(UNKNOWN_FUNCTION) (version 22.12.1.1752 (official build)) , server ClickHouseNode [uri=http://clickhouse:8123/table_group, options={socket_timeout=300000,use_server_time_zone_for_dates=true}]@-196298079

>Solution :

I have run your code and it is working fine:

CREATE TABLE my_table (
    timestamp_column TIMESTAMP WITH TIME ZONE
);

INSERT INTO my_table (timestamp_column)
VALUES 
    ('2023-01-25T05:00:01+03:00'),
    ('2023-01-25T05:01:01+03:00'),
    ('2023-01-25T05:05:01+03:00'),
    ('2023-01-25T05:13:01+03:00'),
    ('2023-01-25T05:14:01+03:00'),
    ('2023-01-25T05:20:01+03:00'),
    ('2023-01-25T05:24:01+03:00'),
    ('2023-01-25T05:29:01+03:00');

SELECT date_trunc('hour', timestamp_column) + (floor(date_part('minute', timestamp_column) / 15) * interval '15 minute') AS interval_start,
       COUNT(*)
FROM my_table
GROUP BY interval_start

enter image description here

In your error message we got info about ClickHouseNode. For ClickHOuse you can use toStartOfInterval instead as the date_part funcion is not avaible there. From the docs it seems to be something like:

toStartOfInterval(t, INTERVAL 15 minute)

but I am not able to test it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading