By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
Help with an interesting Postgres question: Why isn't an Index Only Scan used on a partition accessed via the parent table?.
CREATE TABLE subscriber (
subscriber_id int
, create_timestamp timestamp
);
INSERT INTO subscriber VALUES
(1, date_trunc('year', LOCALTIMESTAMP))
, (2, date_trunc('year', LOCALTIMESTAMP) + interval '1 month')
, (3, date_trunc('year', LOCALTIMESTAMP) + interval '2 month')
, (31, date_trunc('year', LOCALTIMESTAMP) + interval '2 month')
, (32, date_trunc('year', LOCALTIMESTAMP) + interval '2 month')
, (4, date_trunc('year', LOCALTIMESTAMP) + interval '3 month')
, (6, date_trunc('year', LOCALTIMESTAMP) + interval '5 month')
, (11, date_trunc('year', LOCALTIMESTAMP) + interval '8 month')
;
8 rows affected
SELECT month::date, COALESCE(s.count, 0) AS count
FROM generate_series(date_trunc('year', LOCALTIMESTAMP)
, date_trunc('year', LOCALTIMESTAMP) + interval '11 month'
, interval '1 month') m(month)
LEFT JOIN (
SELECT date_trunc('month', create_timestamp) AS month
, count(*) AS count
FROM subscriber
GROUP BY 1
) s USING (month);
month | count |
---|---|
2021-01-01 | 1 |
2021-02-01 | 1 |
2021-03-01 | 3 |
2021-04-01 | 1 |
2021-05-01 | 0 |
2021-06-01 | 1 |
2021-07-01 | 0 |
2021-08-01 | 0 |
2021-09-01 | 1 |
2021-10-01 | 0 |
2021-11-01 | 0 |
2021-12-01 | 0 |