I have a dataset like this
SELECT 'Blue' AS class, [STRUCT('Alice' AS name,18 AS age), STRUCT('Bob' AS name,17 AS age), STRUCT('Charlie' AS name,20 AS age)] as details
I would like to be able to add or access the index of each element of the array like below
SELECT 'Blue' AS class, [STRUCT('Alice' AS name,18 AS age, 1 AS index), STRUCT('Bob' AS name,17 AS age, 2 AS index), STRUCT('Charlie' AS name,20 AS age, 3 AS index)] as details
The ultimate aim is to achieve something like this. So if the index can be accessed on the fly while creating the string_agg, that would be great
with sub as (SELECT 'Blue' AS class, [STRUCT('Alice' AS name,18 AS age, 1 AS index), STRUCT('Bob' AS name,17 AS age, 2 AS index), STRUCT('Charlie' AS name,20 AS age, 3 AS index)] as details
)
select
class,
STRING_AGG('person_'|| index || '_name =' || name || ', person_'|| index || '_age =' || age) AS output
from sub, unnest(details)
group by class
Thanks