The table that currently captures the fiscal periods for our accounting software only includes the END date for each period. I need a query result that fills in all missing dates AND accurately assigns their fiscal period as well.
For instance, here's the last three values in the table now:
| End Date | Fiscal Year | Fiscal Period |
|---|---|---|
| 7/29/2023 | 2023 | 10 |
| 9/2/2023 | 2023 | 11 |
| 9/30/2023 | 2023 | 12 |
I'd like it to return this....
| End Date | Fiscal Year | Fiscal Period |
|---|---|---|
| 7/29/2023 | 2023 | 10 |
| 7/30/2023 | 2023 | 11 |
| 7/31/2023 | 2023 | 11 |
| 8/1/2023 | 2023 | 11 |
| etc. | etc. | |
| 9/2/2023 | 2023 | 11 |
| 9/3/2023 | 2023 | 12 |
| 9/4/2023 | 2023 | 12 |
| 9/5/2023 | 2023 | 12 |
| etc. | etc. | |
| 9/30/2023 | 2023 | 12 |
Is there a way to do that?
I've seen some queries that work to fill in missing dates, but nothing that would also fill in the Fiscal Year and Period for the record right below it (as it's generating each new record).
That's a typical spot for a recursive query:
The first CTE retrieves the date of the "next" period; then, the recursive CTE duplicates the rows, incrementing the current date until it reaches the next one.
Demo on DB Fiddle