【问题标题】:Pivot rows in BigQueryBigQuery 中的数据透视表
【发布时间】:2018-06-11 10:59:53
【问题描述】:

如何在 BigQuery 中进行数据透视?

假设我的桌子是这样的 -

id   event 
----------
1    type 1    
1    type 2    
2    type 2    
2    type 2    
2    type 2     
3    type 1

我想查询这样的东西 -

id type1 type2
----------
1   1    1     
2   0    3
3   1    0

【问题讨论】:

    标签: sql database google-bigquery


    【解决方案1】:

    您可以使用条件聚合:

    select id,
           sum(case when event = 'type 1' then 1 else 0 end) as type1,
           sum(case when event = 'type 2' then 1 else 0 end) as type2
    from t
    group by id;
    

    【讨论】:

    • 知道了。工作谢谢
    • @GovindaTotla 。 . .在 BigQuery 中进行动态数据透视需要编程——我认为,尽管您可以使用数组来接近。
    • 嗯,我刚刚查询了所有的事件类型,只有大约 10 个。所以我只是硬编码的东西,它工作。谢谢顺便说一句
    【解决方案2】:

    你需要有条件的sum()

    select id, sum(case when event = 'type 1' then 1 else 0 end) as type1,
               sum(case when event = 'type 2' then 1 else 0 end) as type2
    from table t
    group by id;
    

    【讨论】:

      猜你喜欢
      • 2021-06-15
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 2016-05-12
      • 2013-10-25
      • 2021-06-10
      • 2016-06-18
      • 2014-12-04
      相关资源
      最近更新 更多