MySQL橫縱表相互轉(zhuǎn)化操作實現(xiàn)方法
本文實例講述了MySQL橫縱表相互轉(zhuǎn)化操作實現(xiàn)方法。分享給大家供大家參考,具體如下:
先創(chuàng)建一個成績表(縱表)
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('張三','數(shù)學(xué)',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('李四','數(shù)學(xué)',100);

再創(chuàng)建一個成績表(橫表)
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);

縱表轉(zhuǎn)橫表
select name,sum(case subjects when '語文' then score else 0 end) as '語文',sum(case subjects when '數(shù)學(xué)' then score else 0 end) as '數(shù)學(xué)', sum(case subjects when '英語' then score else 0 end) as '英語'from user_score group by name;

縱表轉(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;

更多關(guān)于MySQL相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《MySQL查詢技巧大全》、《MySQL事務(wù)操作技巧匯總》、《MySQL存儲過程技巧大全》、《MySQL數(shù)據(jù)庫鎖相關(guān)技巧匯總》及《MySQL常用函數(shù)大匯總》
希望本文所述對大家MySQL數(shù)據(jù)庫計有所幫助。
相關(guān)文章
MySQL創(chuàng)建數(shù)據(jù)庫并支持中文字符的操作方法
這篇文章主要介紹了MySQL創(chuàng)建數(shù)據(jù)庫并支持中文字符的操作方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具體一定的參考借鑒價值,需要的朋友可以參考下2021-01-01
如何解決mysqlimport: Error: 13, Can''t get stat of 的問題
本篇文章是對解決mysqlimport: Error: 13, Can't get stat of問題的方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06
詳解mysql的limit經(jīng)典用法及優(yōu)化實例
這篇文章詳細(xì)介紹了mysql的limit經(jīng)典用法及優(yōu)化實例,有需要的朋友可以參考一下2013-09-09
Mysql5.7及以上版本 ONLY_FULL_GROUP_BY報錯的解決方法
這篇文章主要介紹了Mysql5.7及以上版本 ONLY_FULL_GROUP_BY報錯的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
centos6.4下mysql5.7.18安裝配置方法圖文教程
這篇文章主要為大家詳細(xì)介紹了centos6.4下mysql5.7.18安裝配置方法圖文教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07

