我的问题类似于How to simulate a pivot table with BigQuery?。但是想象一下,你有不可预测的行数,所以你不能在IF语句中列出它们。 那么有没有办法从一列中获取DISTINCT值并从中创建列列表?
答案 0 :(得分:4)
以下非常简单的示例只是为了显示方法:
假设你有temp.example表:
false
并且,假设你想要构建如下所示的查询,但是事先不知道你有多少不同的类别
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)
以下是完全符合此标准的GBQ代码
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
此查询的输出是一个查询,如果您运行它将为您生成枢轴
day 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
答案 1 :(得分:0)
确实可以,但您需要使用自己的编程语言,因为您无法使用SQL查询语言生成SQL语法。