I have a list of Member IDs and they have a START_DATE and END_DATE as is below.
MEMBER_ID | START_DATE | END_DATE |
---|---|---|
1 | 2023-01-01 | 2023-01-31 |
1 | 2023-01-01 | 2023-02-28 |
1 | 2023-01-01 | 2023-03-31 |
But I need a table that lists each month between the minimum start date and maximum end date like this - THIS IS MY DESIRED OUTPUT:
MEMBER_ID | START_DATE |
---|---|
1 | 2023-01-01 |
1 | 2023-02-01 |
1 | 2023-03-01 |
I have tried the below code:
WITH TEST AS
(SELECT MEMBER_ID
,MIN(START_DATE) AS MIN_START_DATE
,MAX(END_DATE) AS MAX_END_DATE
FROM < INSERT TABLE NAME >
GROUP BY MEMBER_ID,
START_DATE,
END_DATE),
CTE AS (
select MEMBER_ID,
dateadd(day, 1 - day(MIN_START_DATE), MIN_START_DATE) as som,
eomonth(MAX_END_DATE) as eom
FROM TEST
GROUP BY MEMBER_ID,
dateadd(day, 1 - day(MIN_START_DATE), MIN_START_DATE),
eomonth(MAX_END_DATE)
union all
select MEMBER_ID, dateadd(month, 1, som), eomonth(dateadd(month, 1, som))
from CTE
where dateadd(month, 1, som) < eom)
select DISTINCT MEMBER_ID, som
from CTE
But the result I get is as below:
MEMBER_ID | som |
---|---|
1 | 2023-01-01 |
1 | 2023-02-01 |
It's not returning the last month that should be 2023-03-01.
I'm probably doing something wrong in the recursive CTE. Any thoughts are appreciated.