问题
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
回答1:
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
回答2:
Try this:
SELECT CONCAT(SURVEY_TAKER_ID, ',', RESPONSE)
FROM (SELECT SURVEY_TAKER_ID, GROUP_CONCAT(RESPONSE) RESPONSE
FROM (SELECT * FROM SURVEY ORDER BY SURVEY_TAKER_ID, QUESTION_NUMBER) A
GROUP BY SURVEY_TAKER_ID
) A
来源:https://stackoverflow.com/questions/20778803/how-to-return-ordered-data-from-multiple-records-into-one-record-in-mysql