简体   繁体   English

Bigquery - 行到列

[英]Bigquery - rows into column

Im trying to convert rows into column (kind of pivot)我正在尝试将行转换为列(一种数据透视)

Current table(generated from a CTE)当前表(从 CTE 生成)

with cte as (select date(start_time) as date, type, count(*) as total 
from table
where start_time >='2020-09-09'
group by 1,2
order by 1)

在此处输入图像描述

My expected output:我预期的 output:

在此处输入图像描述

I tried this query, but it didn't work我试过这个查询,但没有用

with cte as (select date(start_time) as date, type, count(*) as total 
from table
where start_time >='2020-09-09'
group by 1,2
order by 1),
c1 as(
select date,total as C1 from cte where type='c1') ,
c2 as(
select date, total as C2 from cte where type='c2'),
c3 as(
select date,total as C3 from cte where type='c3')
select cte.date,c1.C1,c2.C2,c3.C3  from cte join c1 on cte.date=c1.date join c2 on cte.date=c2.date
join c3 on cte.date=c3.date join ext on cte.date=ext.date

It worked, but every row got added 3 times.它有效,但每一行都添加了 3 次。

Use conditional aggregation:使用条件聚合:

select 
    date(start_time) start_date, 
    countif(cat = 'c1') c1, 
    countif(cat = 'c2') c2, 
    countif(cat = 'c3') c3
from mytable
where start_time >='2020-09-09'
group by date(start_time)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM