【问题标题】:SQL to turn rows into column in snowflakeSQL将行变成雪花中的列
【发布时间】:2021-03-31 22:52:07
【问题描述】:

我在雪花中有一张桌子,如下所示:

有人可以帮我解决这个问题吗?

【问题讨论】:

  • Google 的“SQL 数据透视查询”

标签: sql count pivot aggregate-functions snowflake-cloud-data-platform


【解决方案1】:

使用 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

【讨论】:

    【解决方案2】:

    您可以使用条件聚合:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-19
      • 1970-01-01
      • 2021-04-19
      • 2021-10-05
      • 1970-01-01
      • 2022-10-24
      • 2020-11-24
      • 1970-01-01
      相关资源
      最近更新 更多