Row to column transformation in MySQL

This is called a pivot table. It’s kind of awkward to produce:

SELECT ID, 
 MAX(CASE Type WHEN 202 THEN Degignation END) AS `202`
 MAX(CASE Type WHEN 234 THEN Degignation END) AS `234`
 MAX(CASE Type WHEN 239 THEN Degignation END) AS `239`
 Email
FROM mytable
GROUP BY ID, Email

Note that you must know all the distinct Type values before you write the query. SQL doesn’t allow a result set to add more columns dynamically as it discovers data values in the table. Columns must be fixed at query prepare time.

Leave a Comment