生成两个日期列之间的每个日期的行。

huangapple go评论56阅读模式
英文:

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!

英文:

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 !

答案1

得分: 2

感谢建议!Lukasz的解决方案非常完美。非常感谢!

英文:

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)))
;

生成两个日期列之间的每个日期的行。

huangapple
  • 本文由 发表于 2023年5月23日 01:44:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76308723.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定