【发布时间】:2021-03-31 22:52:07
【问题描述】:
【问题讨论】:
-
Google 的“SQL 数据透视查询”
标签: sql count pivot aggregate-functions snowflake-cloud-data-platform
【问题讨论】:
标签: sql count pivot aggregate-functions snowflake-cloud-data-platform
使用 pivot() 非常简单:
select
*
from
yourtable
pivot(sum(page_view) for "Topic" in ('COLLEGE_SPORTS_OTHER', 'ENTERTAINMENT', 'LOCAL') )
as p
雪花文档:https://docs.snowflake.com/en/sql-reference/constructs/pivot.html
【讨论】:
您可以使用条件聚合:
select account_id,
sum(case when topic = 'COLLEGE_SPORTS_OTHER' then page_view else 0 end) as cnt_college,
sum(case when topic = 'ENTERTAINMENT' then page_view else 0 end) as cnt_entertainment,
sum(case when topic = 'LOCAL' then page_view else 0 end) as cnt_local
from mytable
group by account_id
【讨论】: