bigquery查询结果?

w9apscun  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(260)

我有一张这样的table:

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

我执行这样一个查询,根据小时数将每种类型的计数之和连接起来:

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

我的问题是:没有连接怎么做?我希望一个查询能够处理表中发生的并且事先不知道的任何不同类型的值,这样表就会在每个不同类型的列中增长。
这是可以用bigquery脚本完成的吗?

vsdwdz23

vsdwdz231#

使用 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,则需要将查询构造为字符串,然后运行它。

qvsjd97n

qvsjd97n2#

我还没有尝试过这个方法,但我认为一种可行的方法是对不同的值进行交互,并根据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;

相关问题