在 MYSQL 中实施动态枢轴

Implement Dynamic pivot in MYSQL

我写了一个mysql查询

SELECT id,GROUP_CONCAT(answer.text) as answer,question.question_name as question
FROM user_answers
inner join answer on user_answers.answer_id=answer.answer_id
inner join question on answer.question_id=question.question_id
GROUP BY id,question.question_id

我得到的结果是

但我想要的答案是

如何旋转我的数据。 ?

我试过这个查询。但没有得到实际结果。它的复制

SELECT  id,
     GROUP_CONCAT(
         CASE 
             WHEN question.question_name = 'Household'
             THEN answer.text
             ELSE NULL 
         END
     ) AS Household,
     GROUP_CONCAT(
         CASE 
             WHEN question.question_name = 'Dependents' 
             THEN answer.text
             ELSE NULL 
         END
     ) AS Dependents,
     GROUP_CONCAT(
         CASE 
             WHEN question.question_name = 'Generation'
             THEN answer.text
            ELSE NULL 
         END
     ) AS Generation,
     GROUP_CONCAT(
         CASE 
             WHEN question.question_name = 'Gender' 
             THEN answer.text
             ELSE NULL 
         END
     ) AS 'Gender',
     GROUP_CONCAT(
         CASE 
             WHEN question.question_name = 'Race' 
             THEN answer.text
             ELSE NULL 
         END
     ) AS 'Race',
     GROUP_CONCAT(
         CASE 
             WHEN question.question_name = 'FinancialGoals' 
             THEN answer.text
             ELSE NULL 
         END
     ) AS 'FinancialGoals'
FROM user_answers
inner join answer on user_answers.answer_id=answer.answer_id
inner join question on answer.question_id=question.question_id
GROUP BY id,question.question_id,question.question_name

结果是

添加了激进的功能,但结果列仍在重复

我得到了答案。

SELECT  id,
         GROUP_CONCAT(
             CASE 
                 WHEN question.question_name = 'Household'
                 THEN answer.text
                 ELSE NULL 
             END
         ) AS Household,
         GROUP_CONCAT(
             CASE 
                 WHEN question.question_name = 'Dependents' 
                 THEN answer.text
                 ELSE NULL 
             END
         ) AS Dependents,
         GROUP_CONCAT(
             CASE 
                 WHEN question.question_name = 'Generation'
                 THEN answer.text
                ELSE NULL 
             END
         ) AS Generation
       
    FROM user_answers
    inner join answer on user_answers.answer_id=answer.answer_id
    inner join question on answer.question_id=question.question_id
    GROUP BY id