2

I have a postgres query in which I want to interleave my array_agg statements :

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

Gives me the following:

 5 | ("{""Have you ever received counselling?"",""Have you ever received counselling or mental health support in the past?""}","{1,2}","{yes,no}")

I would like the results to be:

  5 | ("{""Have you ever received counselling?", 1, "yes"",""Have you ever received counselling or mental health support in the past?", 2, "no""}"

How do I do this?

2 Answers 2

3

I've set up a small example similar to yours:

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Better then my solution for sure.
I'm glad to help.
1

To interleave or splice together multiple array_agg's you can do the following:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.