Let say, that I have the following input data:
id | val1 | val2
1 | 1v1 | 1v2
1 | 1v3 | 2v4
2 | 2v1 | 2v2
What I would like to achieve in the output:
id | json
1 | [{"val1":"1v1","val2":"1v2"}, {"val1":"1v3","val2":"1v4"}]
2 | [{"val1":"2v1","val2":"2v2"}]
So all results grouped by id, in JSON array. Multiple rows per ID produces multiple structs in the JSON array.
As the first step I tried to group rows into JSONs using TO_JSON_STRING
function, and ended with code like this:
WITH Input AS (
SELECT id, val1, val2
from My_Table
)
SELECT
t.id,
TO_JSON_STRING(t) AS json_row
FROM Input AS t
But it also puts id
into the target JSON, which I want to avoid.
Any help or hints how to get desirable result from BigQuery will be greatly appreciated.
See the following code:
with data as (
select 1 as id, '1v1' as val1, '1v2' as val2 union all
select 1, '1v3', '2v4' union all
select 2, '2v1', '2v2'
),
grouped as (
select id, array_agg(struct(val1,val2)) x
from data
group by 1
)
select id, to_json_string(x) as json
from grouped
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.