SQL – How to transpose?

MySQL doesn’t support ANSI PIVOT/UNPIVOT syntax, so that leave you to use:

  SELECT t.userid
         MAX(CASE WHEN t.fieldname="Username" THEN t.fieldvalue ELSE NULL END) AS Username,
         MAX(CASE WHEN t.fieldname="Password" THEN t.fieldvalue ELSE NULL END) AS Password,
         MAX(CASE WHEN t.fieldname="Email Address" THEN t.fieldvalue ELSE NULL END) AS Email
    FROM TABLE t
GROUP BY t.userid

As you can see, the CASE statements need to be defined per value. To make this dynamic, you’d need to use MySQL’s Prepared Statement (dynamic SQL) syntax.

Leave a Comment