I have JSONB data that is stored in the data column like so:
...
"dealers": [
{ "dealership":"LHM"},
{ "dealership”:"Camp"},
{ "dealership":"HMA"}
],
"cars": [
{ "name":"Ford"},
{ "name":"BMW" },
{ "name":"Fiat"}
],
...
There are several more attributes which store several more arrays of objects, but for the sake of simplifying my question I only wanted to mention these two.
Firstly, I wanted to see if I could collect all of the name attributes from each object into one field. I found the following question and accepted answer which got me to my initial goal doing something similar to the following:
SELECT
id
, STRING_AGG(car->>'name', ', ')
FROM
autos,
json_array_elements(autos.data->'cars') as car
GROUP BY 1
This results in a single field that looks like this:
Ford, BMW, Fiat
My end goal now is to be able to concatenate all of the other STRING_AGG object attributes from MULTIPLE arrays of objects into one field prepended with a brief description of each, but ONLY if the result of STRING_AGG is NOT EMPTY and NOT NULL (Most important in my case is NOT EMPTY (''). For example, it should look like this:
...//Cars: Ford, BMW, Fiat //Dealerships: LMH, Camp, HMA //... // etc.
I have tried to use CONCAT and CONCAT_WS, and tried utilizing NULLIF but am not sure how to achieve what I am looking for. Particularly, if it is possible to prepend a description string to each STRING_AGG result. Can you assist?
UPDATE: I was able to figure out how to do this with case statements inside of a CONCAT, but I am now wondering if that is a good way to do this or if this can be done in a similar way to S-Man’s given answer. Thank you.