Search code examples
mysqlsqlpivotmysql-workbenchdynamic-pivot

Implement Dynamic pivot in MYSQL


I write an mysql query

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

I am getting a result as

result

But I want the answer as

required

How can I pivot my data. ?

I tried this query . But not getting actual result. its duplicating

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

result is

duplicate

Added aggressive function and still result column is duplicating


Solution

  • I got the answer.

    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