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 MyInfo (
client_id INTEGER NOT NULL,
status VARCHAR(10) NOT NULL,
start_date TIMESTAMP NOT NULL,
end_date TIMESTAMP NULL
);
INSERT INTO MyInfo
(client_id, status, start_date, end_date)
VALUES
(1, 'active', '2020-01-01', '2020-03-15'),
(1, 'inactive', '2020-03-15', null),
(2, 'active', '2020-01-01', null),
(3, 'active', '2020-01-01', '2021-04-28'),
(3, 'inactive', '2021-04-28', '2020-07-28'),
(3, 'active', '2021-07-28', null);
select client_id, extract(year from d) y, extract(month from d) m
from MyInfo t1,
lateral (select generate_series(make_date(cast(extract(year from t1.start_date) as int),
cast(extract(month from t1.start_date) as int), 1),
case when end_date is null then current_date else end_date end,
'1 month'::interval)
) Days(d)
where t1.status = 'active'
order by client_id, y, m;
CREATE TABLE
INSERT 0 6
client_id | y | m |
---|---|---|
1 | 2020 | 1 |
1 | 2020 | 2 |
1 | 2020 | 3 |
2 | 2020 | 1 |
2 | 2020 | 2 |
2 | 2020 | 3 |
2 | 2020 | 4 |
2 | 2020 | 5 |
2 | 2020 | 6 |
2 | 2020 | 7 |
2 | 2020 | 8 |
2 | 2020 | 9 |
2 | 2020 | 10 |
2 | 2020 | 11 |
2 | 2020 | 12 |
2 | 2021 | 1 |
2 | 2021 | 2 |
2 | 2021 | 3 |
2 | 2021 | 4 |
2 | 2021 | 5 |
2 | 2021 | 6 |
2 | 2021 | 7 |
2 | 2021 | 8 |
2 | 2021 | 9 |
2 | 2021 | 10 |
2 | 2021 | 11 |
2 | 2021 | 12 |
2 | 2022 | 1 |
2 | 2022 | 2 |
2 | 2022 | 3 |
2 | 2022 | 4 |
2 | 2022 | 5 |
2 | 2022 | 6 |
2 | 2022 | 7 |
2 | 2022 | 8 |
2 | 2022 | 9 |
2 | 2022 | 10 |
2 | 2022 | 11 |
2 | 2022 | 12 |
2 | 2023 | 1 |
2 | 2023 | 2 |
2 | 2023 | 3 |
2 | 2023 | 4 |
2 | 2023 | 5 |
2 | 2023 | 6 |
2 | 2023 | 7 |
2 | 2023 | 8 |
2 | 2023 | 9 |
2 | 2023 | 10 |
2 | 2023 | 11 |
2 | 2023 | 12 |
2 | 2024 | 1 |
2 | 2024 | 2 |
2 | 2024 | 3 |
2 | 2024 | 4 |
2 | 2024 | 5 |
2 | 2024 | 6 |
2 | 2024 | 7 |
2 | 2024 | 8 |
2 | 2024 | 9 |
2 | 2024 | 10 |
3 | 2020 | 1 |
3 | 2020 | 2 |
3 | 2020 | 3 |
3 | 2020 | 4 |
3 | 2020 | 5 |
3 | 2020 | 6 |
3 | 2020 | 7 |
3 | 2020 | 8 |
3 | 2020 | 9 |
3 | 2020 | 10 |
3 | 2020 | 11 |
3 | 2020 | 12 |
3 | 2021 | 1 |
3 | 2021 | 2 |
3 | 2021 | 3 |
3 | 2021 | 4 |
3 | 2021 | 7 |
3 | 2021 | 8 |
3 | 2021 | 9 |
3 | 2021 | 10 |
3 | 2021 | 11 |
3 | 2021 | 12 |
3 | 2022 | 1 |
3 | 2022 | 2 |
3 | 2022 | 3 |
3 | 2022 | 4 |
3 | 2022 | 5 |
3 | 2022 | 6 |
3 | 2022 | 7 |
3 | 2022 | 8 |
3 | 2022 | 9 |
3 | 2022 | 10 |
3 | 2022 | 11 |
3 | 2022 | 12 |
3 | 2023 | 1 |
3 | 2023 | 2 |
3 | 2023 | 3 |
3 | 2023 | 4 |
3 | 2023 | 5 |
3 | 2023 | 6 |
3 | 2023 | 7 |
3 | 2023 | 8 |
3 | 2023 | 9 |
3 | 2023 | 10 |
3 | 2023 | 11 |
3 | 2023 | 12 |
3 | 2024 | 1 |
3 | 2024 | 2 |
3 | 2024 | 3 |
3 | 2024 | 4 |
3 | 2024 | 5 |
3 | 2024 | 6 |
3 | 2024 | 7 |
3 | 2024 | 8 |
3 | 2024 | 9 |
3 | 2024 | 10 |
SELECT 117