Mysql将表从长格式转换为宽格式

时间:2014-03-28 13:19:03

标签: mysql sql pivot database-table

我有一个像这样的MySQL表:

我希望将它从长格式转换为宽格式,如此

对不起。我是新手,不知道如何发表一张桌子

3 个答案:

答案 0 :(得分:4)

你需要这样的东西:

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;

答案 1 :(得分:2)

试试这个:

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 ;

在这里工作小提琴:http://sqlfiddle.com/#!2/45f29e/2

答案 2 :(得分:-1)

试试这个:

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`;