1

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 !

jyablonski
  • 711
  • 1
  • 7
  • 17
  • 3
    Does this answer your question? [generate\_series() equivalent in snowflake](https://stackoverflow.com/questions/54348801/generate-series-equivalent-in-snowflake) – lemon May 22 '23 at 17:52
  • 1
    *I'm not really seeing any great solutions so far* - ARRAY_GENERATE_RANGE makes it easy https://stackoverflow.com/a/76141254/5070879 MVE: `CREATE OR REPLACE TABLE tab(start_date DATE, end_date DATE, price INT) AS SELECT '2023-05-22', '2023-05-26', 5; SELECT start_date + VALUE::INT AS date, price FROM tab ,TABLE(FLATTEN(ARRAY_GENERATE_RANGE(0, DATEDIFF('DAY',start_date,end_date)+1)));` – Lukasz Szozda May 22 '23 at 17:57

1 Answers1

1

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

jyablonski
  • 711
  • 1
  • 7
  • 17