簡體   English   中英

MySQL將表從長格式轉換為寬格式

[英]Mysql convert table from long format to wide format

我有一個這樣的MySQL表:

我想將其從長格式轉換為寬格式

抱歉。 我是新手,不知道如何張貼表格

您需要這樣的東西:

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;

嘗試這個:

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

嘗試這個:

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 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM