Search code examples
mysqlsqlselectsql-order-bygroup-concat

How to return ordered data from multiple records into one record in MySQL?


I have a MySQL database with a table of survey responses with three important fields (renamed for clarity): SURVEY_TAKER_ID, QUESTION_NUMBER, and RESPONSE. Assuming a 3-question survey as an example, it would look something like this:

SURVEY_TAKER_ID | QUESTION_NUMBER | RESPONSE
----------------------------------------
101               1                 Apple
102               1                 Orange
103               1                 Banana
101               2                 Morning
102               2                 Evening
103               2                 Afternoon
101               3                 Red
102               3                 Blue
103               3                 Yellow

I would like to create a SELECT query that outputs each survey taker's ID and responses in order by question number, e.g.:

101,Apple,Morning,Red
102,Orange,Evening,Blue
103,Banana,Afternoon,Yellow

I know that SQL Server has FOR XML, which can make this easier, but my database is in MySQL, and I must admit that I'm not really all that adept at SQL in the first place. Can anyone please give me a sample query that would produce the output above, or point me to a way to do it?

Many thanks to anyone who can help...

...Jay


Solution

  • SURVEY_TAKER_ID with "Question_Number: RESPONSE" style concating:

    SQL Fiddle

    SELECT SURVEY_TAKER_ID
          ,GROUP_CONCAT(CONCAT(QUESTION_NUMBER, ': ', RESPONSE) ORDER BY QUESTION_NUMBER SEPARATOR ', ') AS RESPONSES
    FROM Table1
    GROUP BY SURVEY_TAKER_ID
    ORDER BY SURVEY_TAKER_ID
    

    .

    SURVEY_TAKER_ID with "RESPONSE" alone style concating:

    SQL Fiddle

    SELECT SURVEY_TAKER_ID
          ,GROUP_CONCAT(RESPONSE ORDER BY QUESTION_NUMBER SEPARATOR ', ') AS RESPONSES
    FROM Table1
    GROUP BY SURVEY_TAKER_ID
    ORDER BY SURVEY_TAKER_ID