I have this table structure:
I'm grouping every element into an array based on the name column:
SELECT json_agg(json_build_object(
'id', id,
'time', time,
'version', version,
'desc1', 'desc1',
'desc2', 'desc2',
))
FROM my_table
GROUP BY name
which gives me this result:
[ { json_agg: [ [Object] ] }, { json_agg: [ [Object] ] } ]
how ever I want the json_agg
key to be the same as the name
column value. like this:
[ { test1: [ [Object] ] }, { test2: [ [Object] ] } ]
How do I achieve this? Using an AS name
doesn't work.
For each grouping, you to build a new object using name
and the aggregated array result in a subquery. Then aggregate the objects created in that subquery into a single array.
SELECT
json_agg(elem) arr
FROM
(
SELECT
json_build_object(
name,
json_agg(json_build_object(
'id', id,
'time', time,
'version', version,
'desc1', 'desc1',
'desc2', 'desc2',
))
) elem
FROM
my_table
GROUP BY
name
) elem
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.