Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
989 views
in Technique[技术] by (71.8m points)

snowflake cloud data platform - Is there a function in SQL that automatically generates more rows by month?

I've got a large database that's got all our transactions and shipping costs from them, here's a simplified version:

Source Table

Date ROUTE Cost
01/20/21 USA to UK $40
01/01/21 USA to UK $40
01/10/21 USA to UK $40
12/20/20 USA to UK $30
11/20/20 USA to UK $20
11/20/20 USA to UK $20
question from:https://stackoverflow.com/questions/65946864/is-there-a-function-in-sql-that-automatically-generates-more-rows-by-month

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is a possible way of doing it by using PIVOT in Snowflake: https://docs.snowflake.com/en/sql-reference/constructs/pivot.html

Let's say "monthname" is a column you extracted out of your "Date"-column, probably this helps:

select * from yourTable
pivot(sum(cost) for monthname in ('January', 'February', 'March', 'April'))
order by route;

The values of your monthname-column should match the one in the brackets.

As this is a more static solution, you still have to adjust the code every month. Here probably writing a stored procedure is helping: https://docs.snowflake.com/en/sql-reference/stored-procedures.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...