Reputation: 87
I have table with one column called cols. I want to separate cols to new column based on type: SKU and MARK using bigquery.
cols
"dsc":[{"amount":30000,"c_amount":0,"d_amount":0,"d_id":"","scope":"CART","title":"Promo","type":"SKU"},{"amount":7000,"c_amount":0,"d_amount":7000,"d_id":"x","scope":"CART_D","title":"","type":"MARK"}]
The result i want is like:
sku_amount sku_c_amount sku_d_amount sku_d_id sku_scope sku_title mark_amount mark_c_amount mark_d_amount mark_d_id mark_scope
30000 0 0 CART Promo 7000 0 0 x CART_D
Anyone know the script? thank you
Upvotes: 0
Views: 56
Reputation: 173190
Consider below approach
create temp table temp_table as
select id1,
max(if(key = 'type', value, null)) over (partition by id1, id2) || '_' || key as key,
value, offset
from (
select md5(cols) as id1, md5(json) id2, arr[offset(0)] as key, arr[offset(1)] as value, offset
from your_table, unnest(json_extract_array('{' || cols || '}', '$.dsc')) json with offset,
unnest(split(translate(json, '{}"', ''))) kv,
unnest([struct(split(kv, ':') as arr)])
);
execute immediate (select '''
select * except(id1) from (select * except(offset) from temp_table)
pivot (any_value(value) for key in ("''' || string_agg(key, '","' order by offset, key) || '''"))
'''
from (select distinct key, offset from temp_table where not ends_with(key, '_type'))
);
if applied to sample data in your question - output is
Upvotes: 1