[英]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 ;
嘗試這個:
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.