Skip to content
Advertisement

Postgres, aggregate result to a single row using values from a column

In Postgres,

I am trying to aggregate results from a table that looks like this:

I would like to return this type of result.

I need the result to be only one row as this is part of a bigger query. I have been trying quite a few things in the last couple of days with my limited Postgres knowledge but haven’t managed to get anything close to what I need.

Some help would be greatly appreciated.

Advertisement

Answer

You can use conditional aggregation and json functions:

Demo on DB Fiddle:

main                                                           | drink                                                        | side                                                          
:------------------------------------------------------------- | :----------------------------------------------------------- | :-------------------------------------------------------------
[{"id": "1", "title": "pizza"}, {"id": "2", "title": "pasta"}] | [{"id": "3", "title": "coke"}, {"id": "4", "title": "beer"}] | [{"id": "5", "title": "fries"}, {"id": "6", "title": "chips"}]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement