From SQL to SPL: Calculate all the year/months included in the year/month interval

The second and third fields of a certain database table are the starting year/month, and the ending year/month, respectively, in the format of "year M month".

Project

ScenarioStart

ScenarioEnd

1

2024M9

2025M3

2

2024M6

2024M10

Now we need to add a calculated column TimePeriods: use the starting year/month and ending year/month to calculate a continuous date sequence with an interval of one month, concatenate them with vertical lines, and keep the date format "year M month" unchanged.

Project

ScenarioStart

ScenarioEnd

TimePeriods

1

2024M9

2025M3

2024M09|2024M10|2024M11|2024M12|2025M01|2025M02|2025M03

2

2024M6

2024M10

2024M06|2024M07|2024M08|2024M09|2024M10

SQL does not have a direct function for generating date sequences, and usually requires JOIN or recursion to indirectly generate multiple records, making the structure very complex. Some databases do not have aggregation functions for concatenating strings after grouping, making it difficult to generate strings in the specified format even if multiple date sequences of records are generated.

SPL can directly generate date sequences and has powerful methods for processing string sets, which can be easily concatenated into a specified format:


 A

1

=dbConn.query("select *, null as TimePeriods from tb”)

2

=A1.run(#4=periods@m(date(#2,"yyyy'M'MM"),date(#3,"yyyy'M'MM"),1).(string(~,"yyyy'M'MM")).concat("|"))

A1 Load data from the database and add a null field called TimePeriods.

A2 Identify the starting year/month and ending year/month in the specified format, generate a date sequence with an interval of one month, convert each member of the sequence into a string in the specified format, and concatenate them with vertical lines. periods()can generate a date sequence, @m represents intervals in month. concat() is used to concatenate a set of strings.

Question sourcehttps://stackoverflow.com/questions/78330406/how-do-i-update-a-sql-table-using-a-generated-variable-on-each-row