Below is my table structure and I want to convert it into another format (From row to column type) I have tried very much but I am not able to do so.
StudentID | Mark | Subject
-------------------------
10 |46 |Java
--------------------------
10 |65 |C#
--------------------------
10 |79 |JavaScript
---------------------------
11 |66 |Java
--------------------------
11 |85 |C#
--------------------------
11 |99 |JavaScript
--------------------------
O/P Should be:
StudentID | Java | C# | JavaScript
---------------------------------
10 | 46 | 65 | 79
---------------------------------
11 | 66 | 85 | 99
-------------------------------
This type of data transformation is known as a pivot. MySQL does not have a pivot function, so you will want to transform the data using an aggregate function with a
CASE
expression.If you know the values ahead of time to transform, then you can hard-code them similar to this:
See SQL Fiddle with Demo.
If the values of the subject are unknown or flexible, then you might want to use a prepared statement to generate dynamic sql:
See SQL Fiddle with Demo.
The result for both queries is: