[英]How to pivot Snowflake table in SQL?
I am trying to show revenue by products and month as a pivot style table.我正在尝试按产品和月份将收入显示为 pivot 样式表。 I have dates ranging back to 2020 but this is something I can filter on when selecting.我的日期可以追溯到 2020 年,但这是我在选择时可以过滤的内容。 Each month may have multiple revenue activity so I am looking for the sum of that entire month, ie show me entire revenue for month of April.每个月可能有多个收入活动,所以我正在寻找整个月的总和,即显示 4 月份的全部收入。
This is an example of information in the existing table这是现有表中的信息示例
product产品 | date_sold销售日期 | revenue收入 |
---|---|---|
software软件 | 2021-11-13 2021-11-13 | $ 1000 $ 1000 |
hardware硬件 | 2022-02-17 2022-02-17 | $ 570 $ 570 |
labor劳工 | 2020-04-30 2020-04-30 | $ 472 $ 472 |
hardware硬件 | 2020-04-15 2020-04-15 | $ 2350 $ 2350 |
I'm not very experienced in sql, but I tried google searching and looking over stackoverflow and this is what I'm tinkering with.我在 sql 方面不是很有经验,但我尝试了谷歌搜索并查看了 stackoverflow,这就是我正在修补的内容。 ` `
SELECT
product,
[1] AS Jan,
[2] AS Feb,
[3] AS Mar,
[4] AS Apr,
[5] AS May,
[6] AS Jun,
[7] AS Jul,
[8] AS Aug,
[9] AS Sep,
[10] AS Oct,
[11] AS Nov,
[12] AS Dec
FROM
(Select
product,
revenue,
date_trunc('month', date_sold) as month
from
fct_final_net_revenue) source
PIVOT
( SUM(revenue)
FOR month
IN ( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] )
) AS pvtMonth;
This is what I'd like the results to look like这就是我想要的结果
product产品 | Jan简 | Feb二月 | Mar三月 | Apr 4月 | May可能 | Jun君 | July七月 | Aug八月 | Sep九月 | Oct十月 | Nov十一月 | Dec十二月 |
---|---|---|---|---|---|---|---|---|---|---|---|---|
Software软件 | 0 0 | 1200 1200 | 1200 1200 | 1200 1200 | 0 0 | 0 0 | 0 0 | 0 0 | 0 0 | 150 150 | 175 175 | 300 300 |
Labor劳工 | 0 0 | 0 0 | 150 150 | 2822 2822 | 150 150 | 150 150 | 150 150 | 150 150 | 0 0 | 0 0 | 0 0 | 0 0 |
Hardware硬件 | 0 0 | 0 0 | 0 0 | 0 0 | 0 0 | 0 0 | 0 0 | 75 75 | 75 75 | 75 75 | 75 75 | 75 75 |
Don't use column names such as month
;不要使用诸如month
之类的列名; avoiding reserved words / key words, etc, makes code easier to read and avoids errors.避免保留字/关键字等,使代码更易于阅读并避免错误。
Then, use MONTH()
to get the month without the year part.然后,使用MONTH()
获取没有年份部分的月份。 Don't truncate to a month, that keeps the year.不要截断到一个月,保持年份。
The pivot then needs to refer to the values in the column being pivotted.然后 pivot 需要引用要透视的列中的值。 Using [1]
implies a column name, however;但是,使用[1]
意味着列名; '1'
is a string and 1
is an integer. '1'
是一个字符串, 1
是一个 integer。
Finally, you can alias the columns from the pivot.最后,您可以为 pivot 中的列添加别名。
SELECT
pvt_month.*
FROM
(
SELECT
product,
revenue,
MONTH(date_sold) AS month_sold
FROM
fct_final_net_revenue
)
AS source
PIVOT
(
SUM(revenue)
FOR month_sold IN (
1,2,3,4,5,6,7,8,9,10,11,12
)
)
AS pvt_month(
product, jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec
)
https://docs.snowflake.com/en/sql-reference/constructs/pivot.html https://docs.snowflake.com/en/sql-reference/constructs/pivot.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.