简体   繁体   中英

How to create new columns from key: value pairs in big query?

I have a table A with the structure:

id key value
1 "abc" "123"
1 "def" "346"
1 "xyz" "789"
2 "abc" "462"
2 "def" "464"
3 "abc" "362"

However this representation proves to be a bit difficult to process in our infra pipelines, so I'm trying to create a new table/materialized view in big query with the following structure:

id "abc" "def" "xyz"
1 "123" "346" "789"
2 "462" "464" NULL
3 "362" NULL NULL

The number of keys is guaranteed to be small (<100). What's the best way to do this using only SQL/JavaScript UDFs in Big Query?

Consider below approach

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

if applied to sample data in your question - output is

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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