I have a data in my database
userid module course total
8 Biophysics A 117
8 BioPhysics B 74
8 BioPhysics C 135
I need the output like
userid module Courses grade
8 BioPhysics Course A: 117 250
Course B: 134
Course C: 35
What you’re trying to accomplish is called “
PIVOTing” row data into separate columns, and it is a feature that is not supported by MySQL, but what you can do is fake it if you know beforehand the range of data you want to pivot into columns.You have a couple of options:
Your example has A, B, and C for
courseperuserid -> modulecombination. Assuming the values incoursecan only be A, B, or C: you can do a conditional aggregation for each value like so:You can add as many
CASEaggregations as you need (for D, E, F, etc.). Keep in mind someuserid -> modulecombinations may haveNULLfor some of the columns if, for instance, it did not contain a row withCforcourse.But if you do not know the range of values beforehand (and perhaps there could be hundreds of different values for
course, you can still get all of the data onto one row, but it wouldn’t be in separate columns – it would actually be one concatenated string in a single column. This is accomplished by usingGROUP_CONCAT():And what this would do is output something like:
Here is a SQL-Fiddle Demo for both options
Edit: As per your comments and edited, here is the new solution: