Skip to content

Instantly share code, notes, and snippets.

@sandcastle
Last active December 8, 2020 22:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sandcastle/efee4af0248eca5157806f01c209e610 to your computer and use it in GitHub Desktop.
Save sandcastle/efee4af0248eca5157806f01c209e610 to your computer and use it in GitHub Desktop.
Time histogram helper function
CREATE OR REPLACE FUNCTION time_histogram(
start_time timestamp,
end_time timestamp
)
RETURNS TABLE(bucket timestamp) AS $$
DECLARE diff_hours int;
BEGIN
diff_hours = abs(extract(epoch from end_time - start_time) / 3600)
raise notice 'diff hours: ', diff_hours;
if diff_hours <= 1 then
select generate_series(
date_trunc('minute', start_time),
date_trunc('minute', end_time),
'1 minute'::interval
) as bucket
;
else if diff_hours <= 24 then
select generate_series(
date_trunc('minute', start_time),
date_trunc('minute', end_time),
'15 minutes'::interval
) as bucket
;
else if diff_hours <= (24 * 7) then
select generate_series(
date_trunc('hour', start_time),
date_trunc('hour', end_time),
'1 hour'::interval
) as bucket
;
end if;
END;
$$ LANGUAGE psql;
select * from time_histogram(
'2020-04-06 08:30:46.85378'::timestamp,
'2020-12-08 15:04:00.516976'::timestamp
);
drop function if exists time_histogram;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment