简体   繁体   English

混淆尝试在 bigquery 中使用 SQL 将行转换为列

[英]Confusion trying to turn rows into columns using SQL in bigquery

I am new to bigquery and I am trying to write an sql query to achieve something specific.我是 bigquery 的新手,我正在尝试编写一个 sql 查询来实现特定的目标。 below is a sample data下面是一个示例数据

|primary_type| year|
|robery      | 2001|
|robery      | 2001|
|robery      | 2002|
|BATTERY     | 2001|
|BATTERY     | 2001|
|BATTERY     | 2002|

the below query is able to generate this下面的查询能够生成这个

select primary_type,
    year,
   count(*) as number_of_crime 
FROM
`bigquery-public-data`
group by primary_type, year
order by year asc;

|primary_type| year|number_of_crime|
|robery      | 2001| 2             |
|robery      | 2002| 1             |
|BATTERY     | 2001| 2             |
|BATTERY     | 2002| 1             |

But the objective is to be able to create this and im not sure how to go about it但目标是能够创建这个,我不确定如何 go

|year|robery|BATTERY|
|2001|2     |2      |
|2002|1     |1      |

Consider below考虑以下

execute immediate format('''
select * from your_table
pivot (count(*) for primary_type in (%s))
''', (select "'" || string_agg(distinct primary_type, "','") || "'" from your_table))              

if applied to sample data in your question - output is如果应用于您问题中的样本数据 - output 是

在此处输入图像描述

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

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