【问题标题】:Generate columns from rows automatically (without IF)自动从行生成列(没有 IF)
【发布时间】:2015-08-26 14:55:43
【问题描述】:

我的问题与How to simulate a pivot table with BigQuery? 类似。但是想象一下你有不可预测的行数,所以你不能在 IF 语句中列出它们。 那么有没有办法从一列中获取 DISTINCT 值并从中创建列列表?

【问题讨论】:

    标签: google-bigquery


    【解决方案1】:

    下面的非常简单的例子只是为了展示方法:

    假设你有 temp.example 表:

    select * from
    (select '2015-08-01' as day, 1 as category, 11 as volume),
    (select '2015-08-01' as day, 2 as category, 21 as volume),
    (select '2015-08-01' as day, 3 as category, 31 as volume),
    (select '2015-08-02' as day, 1 as category, 101 as volume),
    (select '2015-08-02' as day, 2 as category, 201 as volume),
    (select '2015-08-03' as day, 1 as category, 301 as volume),
    (select '2015-08-03' as day, 2 as category, 302 as volume),
    (select '2015-08-03' as day, 4 as category, 304 as volume)
    

    并且,假设您想要构建如下所示的查询,但事先不知道您有多少不同的类别

    select 
       day,
       sum(if(category = 1, volume, 0)) as category_1,
       sum(if(category = 2, volume, 0)) as category_2,
       sum(if(category = 3, volume, 0)) as category_3,
       sum(if(category = 4, volume, 0)) as category_4
    from temp.example
    group by day
    order by day
    

    下面是执行此操作的 GBQ 代码

    select 'select day, ' + 
       group_concat_unquoted('sum(if(category = ' + string(category) + ', volume, 0)) as category_' + string(category)) 
       + ' from temp.example group by day order by day'
    from (select category from temp.example group by category order by category)
    

    这个查询的输出是一个查询,如果你运行它,它将为你生成数据透视

    天 category_1 category_2 category_3 category_4 2015-08-01 11 21 31 0 2015-08-02 101 201 0 0 2015-08-03 301 302 0 304

    【讨论】:

    • 真的是高级 SQL!谢谢!当然它不是动态的,但我认为这是目前最好的解决方案。
    【解决方案2】:

    是的,确实有可能,但您需要使用自己的编程语言,因为您无法使用 SQL 查询语言生成 SQL 语法。

    【讨论】:

    猜你喜欢
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 2021-08-03
    相关资源
    最近更新 更多