Search code examples
mysqlsqlpivotdatabase-table

Mysql convert table from long format to wide format


I have a MySQL table like this:

And I want to convert it from long format to wide format like this

Sorry. I'm new and don't know how to post a table


Solution

  • Try this:

    insert into goodTable 
    select
    bt.id,
    (select bt1.value from badTable bt1 where bt1.info = 'firstname' and bt1.id = bt.id),
    (select bt1.value from badTable bt1 where bt1.info = 'lastname' and bt1.id = bt.id),
    (select bt1.value from badTable bt1 where bt1.info = 'phone' and bt1.id = bt.id)
    from
     badTable bt
    group by id ;
    

    Working fiddle here: http://sqlfiddle.com/#!2/45f29e/2