I have a simple query SELECT name, grp FROM things;, which leads to the following table:
name | grp
------+-----
a | y
b | x
c | x
d | z
e | z
f | z
I would like to get the following single JSON object:
{y: [a], x: [b,c], z: [d,e,f]}
It seems to me that I'm closer to the request SELECT grp, array_agg(name) as names FROM things GROUP BY grp;, which gives three lines with "content" to the array, but I do not know where to go to get the lines compressed into one JSON object.
SELECT json_build_object(grp, array_agg(name)) as objects FROM things GROUP BY grp;may be a little closer, as this leads to a single column of the result of individual JSON objects, such as {y: [a]}, but they are still separate objects, so this may not be the right way to go down.
This uses Postgresql 9.4.
Azdle source
share