i would like convert data from Table1 as you can see on first picture on data in Pivot_table. Is possible to do that in MySQL? Because the values of pivot table(A, B, C, D) are in varchar data format and i cannot use any aggregation function of MySQL like SUM or others.
Table1:
PK Name Subject Grade
-------------------------------------
1 Bob Math A
2 Bob History B
3 Bob Language C
4 Bob Biology D
5 Sue History C
6 Sue Math A
7 Sue Music A
8 Sue Geography C
Pivot_table:
Subject Bob Sue
-------------------------
Math A A
History B C
Language C
Biology D
Music A
Geography C
Thanks for your help
A static query (as far as only Bob and Sue are concerned) might look like this
Now to be able to account for other names use dynamic SQL like this
Output:
Here is SQLFiddle demo
You can wrap it into a stored procedure to simplify things on the calling end
Sample usage:
Here is SQLFiddle demo
Write a stored procedure for the convertion.
SELECT DISTINCT name FROM table1;
to get list of columns for the Pivot_table. Create the table with appropriate number of columns + 1 for Subject.Insert all the subjects in the pivot table to get 1 row for each subject.
INSERT ... from SELECT DISTINCT subject FROM table1
.Create cursor to retrieve all the records from the table1. Go through all the rows of the cursor and for each row call
UPDATE Pivot_table SET [COLUMN_NAME for studetn value]=[grade value] WHERE subject=[subject name value];