我有一个postgres查询,我想在其中交换我的array_agg语句:
SELECT client_user_id,
(array_agg(question), array_agg(client_intake_question_id), array_agg(answer)) as answer
FROM client_intake_answer
LEFT OUTER JOIN client_intake_question
ON client_intake_question.id = client_user_id
GROUP BY client_user_id
给我以下内容:
5 | ("{""Have you ever received counselling?"",""Have you ever received counselling or mental health support in the past?""}","{1,2}","{yes,no}")
我希望结果如下:
5 | ("{""Have you ever received counselling?", 1, "yes"",""Have you ever received counselling or mental health support in the past?", 2, "no""}"
我该怎么做?
答案 0 :(得分:3)
我已经设置了一个类似于你的小例子:
create table answers(user_id int, question_id int, answer varchar(20)); create table questions(question_id int, question varchar(20)); insert into questions values (1, 'question 1'), (2, 'question 2'); insert into answers values (1, 1, 'yes'), (1, 2, 'no'), (2, 1, 'no'), (2, 2, 'yes');
select user_id, array_agg(concat(questions.question, ',', questions.question_id::text, ',', answers.answer)) from questions inner join answers on questions.question_id = answers.question_id group by answers.user_id
user_id | array_agg ------: | :------------------------------------- 1 | {"question 1,1,yes","question 2,2,no"} 2 | {"question 1,1,no","question 2,2,yes"}
dbfiddle here
答案 1 :(得分:1)
要将多个array_agg交错或拼接在一起,您可以执行以下操作:
SELECT client_user_id,
array_agg('[' || client_intake_question_id || question || ',' || answer || ']') as answer
FROM client_intake_answer
LEFT OUTER JOIN
client_intake_question ON client_intake_question.id = client_user_id
GROUP BY client_user_id