Skip to content
Advertisement

BigQuery: How to aggregate records in a STRUCT or JSON field?

I want to aggregate a pair of columns as a dictionary of key,value pairs to construct a STRUCT or a JSON STRING over multiple records.

Currently my implementation leverages the STRING nature of JSON & STRING_AGG to build such a JSON value:

Which results in the following:

Is there a more readable approach? Kind of a STRUCT_AGG(key_field STRING, value_field ) or equivalently signed JSON_DICT_AGG/JSON_STRUCT_AGG?

Advertisement

Answer

Consider below approach

with output

enter image description here

If you want to wrap up this into UDF – see below example

And btw, you can do exactly same “trick” with your own version – as in below example

All with same output already presented on the top of the answer

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement