自动从行生成列(无 IF)

Generate columns from rows automatically (without IF)

我的问题与此类似How to simulate a pivot table with BigQuery?。但是假设您有不可预测的行数,因此您不能在 IF 语句中列出它们。 那么有什么方法可以从一列中获取 DISTINCT 值并从中创建列列表吗?

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

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

假设您有 temp.example table:

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)

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

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)

这个查询的输出是一个查询,如果你运行它

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