0

I have the following table:

surveys
comp_id    question
4          What is your name?
4          How are you?
4          Where do you live?
5          Who are you?
5          What is your birthday?

I need help writing a Query that gives me the following output:

comp_id    my_questions
4          What is your name?How are you?Where do you live?
5          Who are you?What is your birthday?

Thanks,

7
  • 3
    group_concat(). but why do you want to 'destroy' your text like this? Commented Dec 13, 2012 at 20:47
  • Is there a grouping function in SQL that does this? Commented Dec 13, 2012 at 20:48
  • @jamis0n group_concat does exactly what he needs! Commented Dec 13, 2012 at 20:49
  • @Marc B: What do you mean destroy? Commented Dec 13, 2012 at 20:49
  • Awesome! Learned something new! Commented Dec 13, 2012 at 20:50

1 Answer 1

2

You are looking for the GROUP_CONCAT() function. Use it like this:

SELECT comp_id, GROUP_CONCAT([DISTINCT] question [ORDER BY some_field ASC/DESC] [SEPARATOR '']) as my_questions
FROM surveys
GROUP BY comp_id

Note I have shown some some optional values to pass into GROUP_CONCAT in []. To get exact like you are showing just use GROUP_CONCAT(question SEPARATOR ''). The optional items let you look for distinct question values or order them by any field(s) (including question itself).

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

6 Comments

I'm doing the following query but it doesn't seem to work: "SELECT GROUP_CONCAT(question) AS Questions FROM surveys WHERE question_code = 1 AND question_code = 2"
You need a GROUP BY clause on some field. I am actually surprised this didn't produce MySQL error as most aggregate functions do when no GROUP BY is present.
so if I put 'GROUP BY comp_id' without selecting comp_id, it will work?
Yes, you don't need to SELECT a field in order to use GROUP BY on it.
This is because you are not selecting any records. How can a record have question_code = 1 AND question_code = 2. A single record can have one value or the other, not BOTH. You probably need to use WHERE question_code IN (1,2) or WHERE question_code = 1 OR question_code = 2. The first is probably better code for dynamic queries where number of values of question_code that you are filtering on might vary.
|

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.