Simple way to cluster times from a SQL query

159 Views Asked by At

With a database schema similar to

timestamp
metric
filter_dimensions
time_bucket (HH:MM)

I want to make a query that fetches information from the last x amount of days, with time buckets being y consecutive buckets. I then want to aggregate the given metric over the y days. So lets say we want to query for a time bucket of 9:55-10:05 for the last 14 days. We should get 10 records returned per day for 14 days leading to 140 total. I then want to aggregate those daily records so I get one record for each day. This is very simple if I just want time bucket since it's

SELECT metric FROM table WHERE
    filter_dimensions = whatever AND
    timestamp > now() - 14d AND
    time_bucket = 9:55

With a range of time_bucket we can do something like

SELECT SUM(metric) FROM table WHERE
    filter_dimensions = whatever AND
    timestamp > now() - 14d AND
    time_bucket >= 9:55 AND 
    time_bucket < 10:55
GROUP BY
    day(timestamp)

However this fails when we're checking for a timestamp range crossing over midnight such as [11:55, 00:05]

Currently my best way to handle this is to either add another column to the table so that the time range (10m in this case) is a field. Another option is in the code we can implement some logic to cluster the results. However I'm hoping there's a way to make the query return this directly.

Thank you.

0

There are 0 best solutions below