Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 326
Luvias Avatar asked Dec 10 '25 09:12

Luvias


2 Answers

You need something like this:

select id,
       max(case when info='firstname' then value else null end), 
       max(case when info='lastname' then value else null end), 
       ...
   from table
   group by id;

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

like image 31
Hackerman Avatar answered Dec 11 '25 23:12

Hackerman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!