Skip to content
Advertisement

PostgreSQL count of each status per day

I have the following table:

I also have a table with every calendar day from 2019-11-01 to 2019-12-31.

I need to find out how many occurrences of each status exist per calendar day for the time span listed above.

If a status is Opened on 2019-12-14 and Pending on 2019-12-17, I need to count that it was Opened for every day from 2019-12-14 to 2019-12-17.

Ideal:

Any help is greatly appreciated.

Edit: The solution from GMB below is very close, but it leaves me with the following table:

How do I add the end date to my range (2019-12-31) to the missing column values?

Advertisement

Answer

Consider the following query:

This works by cross-joining the calendar table with the list of distinct status available in the table, and then joining it with a subquery that uses lead() to get the date of the next status associated to each record. If you have a table of statuses, you can use it instead of the subquery that selects the distinct statuses.

Demo on DB Fiddle:

dt                     | status    | count
:--------------------- | :-------- | ----:
2019-11-12 00:00:00+00 | Completed |     0
2019-11-12 00:00:00+00 | Opened    |     1
2019-11-12 00:00:00+00 | Pending   |     0
2019-11-13 00:00:00+00 | Completed |     0
2019-11-13 00:00:00+00 | Opened    |     1
2019-11-13 00:00:00+00 | Pending   |     0
2019-11-14 00:00:00+00 | Completed |     0
2019-11-14 00:00:00+00 | Opened    |     2
2019-11-14 00:00:00+00 | Pending   |     0
2019-11-15 00:00:00+00 | Completed |     0
2019-11-15 00:00:00+00 | Opened    |     1
2019-11-15 00:00:00+00 | Pending   |     1

Note that the DB Fiddle demonstrates how to use handy Postgres function generate_series() to fill in the calendar table.

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