I have a table that looks like the following
PIN QuestionNum Response
1111 1 1
1111 2 3
2222 1 4
2222 2 3
3333 2 5
The expected output from my query would be:
PIN Question1 Question2
1111 1 3
2222 4 3
3333 null 5
I don’t know if it is possible to make the output of a query appear like this.
Could anyone please advise if this is possible please.
This is basically a
PIVOTbut MySQL does not havePIVOTfunction. So you will want to replicate this using an aggregate function and aCASEstatement. If you know the number ofQuestionNumvalues that you have then you can hard-code the query similar to this:See SQL Fiddle with Demo
Now, if you have an unknown number of values for
QuestionNum, then you can use a prepared statement to generate a dynamic version of this query:See SQL Fiddle with Demo
Both will produce the same results: