I want to create one row per id per month till the month of end_date
.
e.g. first customer id
started in Oct and ended in Nov. So I want to get two rows for each month that the customer was active. Besides that, I want to create a column that flags if it was active in that month.
| id | start_date | end_date |
|----|------------|------------|
| a | 2021-10-02 | 2021-11-15 |
| b | 2021-11-13 | 2021-11-30 |
| c | 2021-11-16 | |
When there is no end_date
, meaning it is still active, it has to be till the current month.
Example data:
WITH t1 AS (
SELECT 'a' AS id, '2021-10-02'::date AS start_date, '2021-11-15'::date AS end_date UNION ALL
SELECT 'b' AS id, '2021-11-13'::date AS start_date, '2021-11-30'::date AS end_date UNION ALL
SELECT 'c' AS id, '2021-11-16'::date AS start_date, NULL::date AS end_date
)
The expected result:
| id | start_date | end_date | months | is_active |
|----|------------|------------|------------|-----------|
| a | 2021-10-02 | 2021-11-15 | 2021-10-01 | TRUE |
| a | 2021-10-02 | 2021-11-15 | 2021-11-01 | FALSE |
| b | 2021-11-13 | 2021-11-30 | 2021-11-01 | FALSE |
| c | 2021-11-16 | | 2021-11-01 | TRUE |
| c | 2021-11-16 | | 2021-12-01 | TRUE |
| c | 2021-11-16 | | 2022-01-01 | TRUE |
How can I achieve that in Snowflake?