[英]Postgresql extract multiple values into different columns
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.但是,当我想提取 soda_painpoints 时,它只会返回第一个值。 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
首先,要将答案连接到 jsonb 对象中,您应该使用jsonb_object_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
'{' || 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.那么soda_painpoints
问题的答案 '1 5 8 7' 似乎是一个字符串,它连接了由空格字符分隔的整数 (1, 5, 8, 7) 列表。 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 :在这种情况下,您可以将 Answer 存储为简单的 jsonb 数值或 jsonb 数组,具体取决于 Answer 值的类型:
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.这样做,与键soda_painpoints
关联的值将是一个 jsonb 整数数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.