Skip to content
Advertisement

use Enddate to generate Months(Dates) to Enddates in SQL

I have a table as below:

I want to generate from the table above to return ID, Enddate, MRR and Month as shown

Note the Month column of example ID = 2 consist of next month up to the enddate. The same applies to ID of 3 and 5. However, ID 1 and 4 Has NULL because we are in May 2020 and it is skip because enddate didn’t have future date.

I wrote a code by i didn’t get it right so i needed help.

This is the code I have. But it’s just for ID=5 but I can’t figure out how to add ID, Enddate and MRR. And it is not dynamic for other IDs.

/End Date/ and /Start Date/ shows represent the code that follow them

Advertisement

Answer

You can use a recursive CTE to generate the list of dates, finding the first day of the next month and then adding a month until the Enddate:

Output is too long to show here but as desired. Demo on SQLFiddle

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement