سؤال

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

هل كانت مفيدة؟

المحلول 2

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

نصائح أخرى

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:

SELECT  P.`info`,
        (CASE 
            WHEN P.`action`='fname' AND P.`id` = '1'OR'2' 
            THEN P.`id` 
            ELSE NULL 
        END)AS 'firstname',

        (CASE 
            WHEN P.`action`='lname' AND P.`id` = '2' OR'2'
            THEN P.`id` 
            ELSE NULL 
        END) AS 'lastname',

        (CASE 
            WHEN P.`action`='phone' AND P.`id` = '1'OR'2' 
            THEN P.`id` 
            ELSE NULL 
        END) AS 'phone'
FROM    tablename P
GROUP BY P.`info`;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top