I need your help with a survey. The raw table is in the following format:
I need to convert the information into columns however in some cases there can be multiple values for an answer.
The desired output would be the following:
I managed to concatenate the answers into a list with the following code:
'{' || ARRAY_TO_STRING(ARRAY_AGG('"' || Question || '":' || Answer),',') || '}' AS key_value
Then using this column I could extract it with:
CAST(COALESCE(key_value::JSON ->> 'consumption_soda','0') AS INTEGER) AS soda_consumption,
CAST(COALESCE(key_value::JSON ->> 'consumption_water','0') AS INTEGER) AS water_consumption
However, when I wanted to extract soda_painpoints it will only return the first value. Could you please help me find an answer to my problem?
First, to concatenate the answers into a jsonb object, you should use jsonb_object_agg(Question, Answer) AS key_value
instead of '{' || ARRAY_TO_STRING(ARRAY_AGG('"' || Question || '":' || Answer),',') || '}' AS key_value
'{' || ARRAY_TO_STRING(ARRAY_AGG('"' || Question || '":' || Answer),',') || '}' AS key_value
'{' || ARRAY_TO_STRING(ARRAY_AGG('"' || Question || '":' || Answer),',') || '}' AS key_value
.
Then the Answer '1 5 8 7' for the soda_painpoints
Question seems to be a string which concatenates a list of integers (1, 5, 8, 7) separated by a space character. In this case, you can store the Answer as a simple jsonb numeric value or as a jsonb array depending on the type of the Answer value :
SELECT jsonb_object_agg( Question
, CASE
WHEN jsonb_typeof(to_jsonb(Answer)) = 'number'
THEN Answer :: integer
ELSE regexp_split_to_array(Answer, '\s+') :: integer[]
END
) AS key_value
Doing so, the value associated to the key soda_painpoints
will be a jsonb array of integers.
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.