MySQL – Rows to Columns

MySQL

I have a table with 3 columns, participant_id, question, answer. for each participant, there will be five question.

How do fetch a report like against each participant each question as a column header and answer as value. So in report for each participant there will be one entry in report?

table structure:

expected output:
group using participant_id and each question should be the column header and custtusponding answer will be the column value.

Best Answer

This is similar to pivot table , Try This

create view pivot_questions as (
  select
    questions.*,
    case when question = "question1" then itemvalue end as question1,
    case when itemname = "question2" then itemvalue end as question2,
    case when itemname = "question3" then itemvalue end as question3,
    case when itemname = "question4" then itemvalue end as question4,
    case when itemname = "question5" then itemvalue end as question5
  from questions
);

select * from pivot_questions;