在Big Query中透视行

时间:2018-06-11 10:59:53

标签: sql database google-bigquery

如何在Big Query中进行数据透视?

假设我的表就像 -

id   event 
----------
1    type 1    
1    type 2    
2    type 2    
2    type 2    
2    type 2     
3    type 1

我想查询类似的内容 -

id type1 type2
----------
1   1    1     
2   0    3
3   1    0

2 个答案:

答案 0 :(得分:2)

您可以使用条件聚合:

select id,
       sum(case when event = 'type 1' then 1 else 0 end) as type1,
       sum(case when event = 'type 2' then 1 else 0 end) as type2
from t
group by id;

答案 1 :(得分:1)

您需要有条件的sum()

select id, sum(case when event = 'type 1' then 1 else 0 end) as type1,
           sum(case when event = 'type 2' then 1 else 0 end) as type2
from table t
group by id;