I have the following query, which returns the values correctly.
SELECT date_trunc('hour', created_at) as date,
CAST(COUNT(case when subscription = true then id end) AS INTEGER) as subscriptions,
CAST(COUNT(case when subscription = false then id end) AS INTEGER) as unsubscriptions
FROM requests
GROUP BY date
ORDER BY date
Output:
| date | subscriptions | unsubscriptions |
|---|---|---|
| 2021-01-14 23:00:00.000000 +00:00 | 1 | 2 |
| 2021-01-14 20:00:00.000000 +00:00 | 10 | 1 |
| 2021-01-14 18:00:00.000000 +00:00 | 0 | 1 |
| ... | ... | ... |
The problem is that i need the missing hours of the day even if there are not any entries in the table, with 0 count.
Expected output:
| date | subscriptions | unsubscriptions |
|---|---|---|
| 2021-01-14 23:00:00.000000 +00:00 | 1 | 2 |
| 2021-01-14 22:00:00.000000 +00:00 | 0 | 0 |
| 2021-01-14 21:00:00.000000 +00:00 | 0 | 0 |
| 2021-01-14 20:00:00.000000 +00:00 | 10 | 1 |
| 2021-01-14 19:00:00.000000 +00:00 | 0 | 0 |
| 2021-01-14 18:00:00.000000 +00:00 | 0 | 1 |
| ... | ... | ... |
Table Structure:
| id | subscription | created_at |
|---|---|---|
| int | bool | timestamp |