您好,登錄后才能下訂單哦!
這篇文章主要講解了MySQL如何實現橫縱表相互轉化,內容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。
本文實例講述了MySQL橫縱表相互轉化操作實現方法。分享給大家供大家參考,具體如下:
先創建一個成績表(縱表)
create table user_score ( name varchar(20), subjects varchar(20), score int ); insert into user_score(name,subjects,score) values('張三','語文',60); insert into user_score(name,subjects,score) values('張三','數學',70); insert into user_score(name,subjects,score) values('張三','英語',80); insert into user_score(name,subjects,score) values('李四','語文',90); insert into user_score(name,subjects,score) values('李四','數學',100);
再創建一個成績表(橫表)
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);
縱表轉橫表
select name,sum(case subjects when '語文' then score else 0 end) as '語文',sum(case subjects when '數學' then score else 0 end) as '數學', sum(case subjects when '英語' then score else 0 end) as '英語'from user_score group by name;
縱表轉橫表
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如何實現橫縱表相互轉化有進一步的了解,如果還想學習更多內容,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。