sqlsnowflake-cloud-data-platform

Snowflake Generate row for every date between 2 date columns


I'm working in Snowflake trying to explode rows in a table where each row is currently based on a date range provided by start_date and end_date columns. I need to turn this information into a single row for every date in that date range.

Below is my current table as of right now. In this example there's a row with a date range that spans 5 days with a price of $5, so I want to turn this 1 row into 5 rows for every date in that date range while retaining that same pricing information of $5 for every row.

start_date end_date price
2023-05-22 2023-05-26 5

Proposed Solution 1

start_date end_date price
2023-05-22 2023-05-22 5
2023-05-23 2023-05-23 5
2023-05-24 2023-05-24 5
2023-05-25 2023-05-25 5
2023-05-26 2023-05-26 5

Proposed Solution 2

date price
2023-05-22 5
2023-05-23 5
2023-05-24 5
2023-05-25 5
2023-05-26 5

Either solution will work for my use case. In Postgresql i've used generate_series and had good results, but while researching this for Snowflake I'm not really seeing any great solutions so far. Any help would be appreciated !


Solution

  • Thanks for the suggestions! Lukasz solution is perfect. Much appreciated!

    select
        date(start_date) + value::int as date,
        price
    from pricing_table,
         table(flatten(array_generate_range(0, datediff('day', start_date, end_date) + 1)))
    ;
    

    enter image description here