Skip to content
Advertisement

How to generate dynamic table having begin month date and end month date Teradata or SAS SQL

I’d like to generate a dynamic Table with the start date of a month as a column and the end date of the month as another column.

Ideally, I’d like to provide two years, f.e. 2016 and 2021. The output I’d like to have when providing these two years is the following:

Kindly note that I require the output for all years from 2016 to 2021. In my example above this would mean that 2017 2018 2019 2020 should be included.

I have tried to play with a time series function of Teradata but failed to get results.

The solution I tried to recreate in Teradata is this one: How to generate calendar table having begin month date and end month Date

Furthermore, I have tried the EXPAND ON PERIOD time series function of Teradata.

Advertisement

Answer

I’m sure there are some fancy ways of doing this, but I think just hitting up the built-in calendar table is probably the easiest:

To do this without a table reference, it gets a little ugly. EXPAND ON seems like an obvious route, but it errors if there is no table reference in the FROM clause. UNION suffers from the same issue, but we can cheat with UNION by using a cte. EXPAND ON is more picky and to trick it we can hijack Teradata’s JSON_TABLE feature:

You could also go with a recursive CTE to build out the months, which feels less hacky, but takes longer to generate.

I’d be very interested if there is a more elegant way to pull this off. Without dual or sequence generation like are present in other RDBMS, the options to build data sets with no table reference are pretty limited.

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