溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

MySQL如何實(shí)現(xiàn)橫縱表相互轉(zhuǎn)化

發(fā)布時(shí)間:2020-07-18 15:12:52 來(lái)源:億速云 閱讀:954 作者:小豬 欄目:MySQL數(shù)據(jù)庫(kù)

這篇文章主要講解了MySQL如何實(shí)現(xiàn)橫縱表相互轉(zhuǎn)化,內(nèi)容清晰明了,對(duì)此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。

本文實(shí)例講述了MySQL橫縱表相互轉(zhuǎn)化操作實(shí)現(xiàn)方法。分享給大家供大家參考,具體如下:

先創(chuàng)建一個(gè)成績(jī)表(縱表)

create table user_score
(
  name varchar(20),
  subjects varchar(20),
  score int
);
insert into user_score(name,subjects,score) values('張三','語(yǔ)文',60);
insert into user_score(name,subjects,score) values('張三','數(shù)學(xué)',70);
insert into user_score(name,subjects,score) values('張三','英語(yǔ)',80);
insert into user_score(name,subjects,score) values('李四','語(yǔ)文',90);
insert into user_score(name,subjects,score) values('李四','數(shù)學(xué)',100);

MySQL如何實(shí)現(xiàn)橫縱表相互轉(zhuǎn)化

再創(chuàng)建一個(gè)成績(jī)表(橫表)

create table user_score2
(
  name varchar(20),
  yuwen int,
  shuxue int,
  yingyu int
);
insert into user_score2(name,yuwen,shuxue,yingyu) values('張三',60,70,80);
insert into user_score2(name,yuwen,shuxue,yingyu) values('李四',90,100,0);

MySQL如何實(shí)現(xiàn)橫縱表相互轉(zhuǎn)化

縱表轉(zhuǎn)橫表

select name,sum(case subjects when '語(yǔ)文' then score else 0 end) 
as '語(yǔ)文',sum(case subjects when '數(shù)學(xué)' then score else 0 end) 
as '數(shù)學(xué)', sum(case subjects when '英語(yǔ)' then score else 0 end) 
as '英語(yǔ)'from user_score group by name;

MySQL如何實(shí)現(xiàn)橫縱表相互轉(zhuǎn)化

縱表轉(zhuǎn)橫表

SELECT  name,'yuwen'  AS   subjects,yuwen  AS  score  FROM  user_score2  UNION  ALL  
SELECT  name,'shuxue'  AS   subjects,shuxue  AS  score  FROM  user_score2 UNION  ALL  
SELECT  name,'yingyu'  AS   subjects,yingyu  AS  score  FROM  user_score2 
ORDER BY name,subjects DESC; 

MySQL如何實(shí)現(xiàn)橫縱表相互轉(zhuǎn)化

看完上述內(nèi)容,是不是對(duì)MySQL如何實(shí)現(xiàn)橫縱表相互轉(zhuǎn)化有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI