Skip to content
Advertisement

Grouped aggregate counts for each date in a series of dates

I am trying to get grouped task counts by state over a series of dates using the following tables:

There isn’t a consistent daily “state” record for each task because task_logs only has entries for when a task changes state. This means I have to get the last “state change” log for each task prior to a specified date. I’ve got the following query working to get the task count in each state for one day ago:

My trouble comes from trying to combine the query above with generate_series to get the daily count over a series of dates, something like:

Here’s a dbfiddle setup with the tables above. Any thoughts/ideas on how to perform the query above (or rewrite it) for each date in a series of dates (generate_series(current_date - interval '5 day', current_date, '1 day')) would be greatly appreciated!

Advertisement

Answer

Consider a stored function to loop through the generated series of dates and capture each daily aggregated snapshot:

Online Demo

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement