【问题标题】:BigQuery query result having variable number of columns?BigQuery 查询结果的列数可变?
【发布时间】:2020-09-20 23:25:20
【问题描述】:

我有一张这样的表格:

TIME  TYPE COUNT
00:01 DOG  4
00:04 CAT  5
00:07 DOG  2
00:30 BIRD 1
01:04 DOG  2
01:30 BIRD 3
01:40 DOG  1
02:01 BIRD 4

我做了一个这样的查询,根据小时加入每个 TYPE 的 COUNT 总和:

select HOUR(`TIME`), `TYPE`, sum(`COUNT`)
from `table`
where `TYPE` = 'DOG'
group by HOUR(`TIME`)
FULL JOIN
...(same query but... where `TYPE` = 'CAT')
ON hour...
FULL JOIN
...(same query again, but where `TYPE` = 'BIRD')
etc.

目的是得到这样的结果:

HOUR DOG CAT BIRD
00   6   5   1
01   5   0   3
02   0   0   4

我的问题是:如果没有连接,你怎么能做到这一点? 我希望查询适用于发生在表中并且预先不知道的任何不同 TYPE 值,因此该表将在每个不同 TYPE 的列中增长。

这可以通过 BigQuery 脚本完成吗?

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    使用sum(case . . ):

    select extract(hour from time), 
           sum(case when type = 'dog' then count else 0 end) as dog,
           sum(case when type = 'cat' then count else 0 end) as cat,
           sum(case when type = 'bird' then count else 0 end) as bird
    from t
    group by extract(hour from time);
    

    对于这个版本,您需要明确列出每个值。如果需要动态 SQL,则需要将查询构造为字符串,然后运行。

    【讨论】:

      【解决方案2】:

      我没有尝试过,但我认为可行的一种方法是根据 Gordon Linoff 的回答对不同的值进行交互并生成查询:

      # Get array of distinct types
      DECLARE myTypes ARRAY<STRING>;
      SET myTypes = ( select distinct(`TYPE`) form `table`);
      
      # get size of array
      DECLARE x INT64;
      SET x = ARRAY_LENGTH(myTypes);
      
      # start making query
      DECLARE myQuery STRING;
      SET myQuery = "select extract(hour from time),";
      
      LOOP
      
          x = x-1;
      
          # Add column for each type
          SET myQuery = CONCAT(myQuery,format("sum(case when type = '%s' then count else 0 end) as %s,",myTypes[OFFSET(x)]);
      
          IF x == 0 THEN LEAVE;
          END IF;
      END LOOP;
      
      #finish up query
      SET myQuery = CONCAT(myQuery,"from table group by extract(hour from time)")
      
      
      EXECUTE IMMEDIATE myQuery;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多