You need aggregation functions in your query:
select last_name,
max(case when question_number = 1 then result end) as Q1,
max(case when question_number = 2 then result end) as Q2,
max(case when question_number = 3 then result end) as Q3,
max(case when question_number = 4 then result end) as Q4
from test_case
group by last_name;
In most databases, your version of the query would not compile. You would get an error to the effect that question_number
is not in the group by
clause. MySQL allows the syntax, but then just returns arbitrary values for a single row. The max()
makes sure that all the rows are processed.