I have a table named mdl_grade_grades with columns id, userid, itemid, rawgrademax, finalgrade I have another table mdl_grade_items with id, itemname where itemid in mdl_grade_grades = id in mdl_grade_items
I am using MySQL database and number of items will differ in different cases.
I have researched a lot for last 3 days but my MySQL skills are not that enriched to understand and modify the related solutions available. Still I tried to modify the queries provided in following threads: MySQL dynamic pivot table MySQL Table pivot - Dynamic
But, I get an error near "PREPARE stmt FROM @sql;"
I tried this:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when itemid = ''',
itemid,
''' then finalgrade end) AS `',
itemid, '`'
)
) INTO @sql
FROM mdl_grade_grades;
SET @sql = CONCAT('SELECT userid, ', @sql, '
FROM mdl_grade_grades
GROUP BY userid');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
I want output like shown below Desired Output
So, the item names will become headers and their value will be equal to (finalgrade / rawgrademax) * 100 whereever user has a record. If user does not have a record for the item, the value for that item will remain blank.