I have this table:
idSection | idQuestion | title | enunciation | total | name
1 | 1 | title 1 | question 1 | 5 | Good
1 | 1 | title 1 | question 1 | 3 | Very Good
1 | 1 | title 1 | question 1 | 1 | Bad
1 | 2 | title 2 | question 2 | 1 | Good
1 | 2 | title 2 | question 2 | 3 | Bad
1 | 3 | title 3 | question 3 | 1 | Bad
How can I make the column values name in multiple columns.
Here is the expected result:
title | enunciantion | bad | good | very good
title 1 | question 1 | 1 | 5 | 3
title 2 | question 2 | 3 | 1 | 0
title 3 | question 3 | 1 | 0 | 0
I don't know how many columns there will be (it's dynamic).
NEW EDIT:
title | enunciantion | Column0 | Column1 | Column2 | ... | Column7 |
0 | 0 | bad | good |very good| ... | 0 |
title 1 | question 1 | 1 | 5 | 3 | ... | 0 |
title 2 | question 2 | 3 | 1 | 0 | ... | 0 |
title 3 | question 3 | 1 | 0 | 0 | ... | 5 |
Now, the only difference is that instead of having dynamic columns, there are only static columns, however the first row of the table is such dynamic values ranging look at another table.
For MySQL:
SQL Fiddle Demo
For SQL Server:
SQL Fiddle DemoSQL Server
Update:
If these values
good, bad, very good
are coming form another table and you want to do this dynamically.For MySQL:
SQL Fiddle DemoMySQL, dynamic
For SQL Server you can do this:
SQL Fiddle DemoSQL Server, dynamic
This will give you:
Just to expand on @Mahmoud Gamal's answer on the dynamic SQL version for SQL server. If you want to replace the
null
values with zeros, then you can use the following:See SQL Fiddle with Demo
The result is: