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数据库计有所帮助。

到此这篇关于MySQL横纵表相互转化操作如何实现方法就介绍到这了。过好每一天,认真工作,努力学习学他人知识,变自已财富,学他人长处,补自已不足!让自已在众人的眼光里光彩夺目。努力回报给予想要的一切,人生真的太,简单得只要脚踏实地就行!更多相关MySQL横纵表相互转化操作如何实现方法内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!

您可能有感兴趣的文章
MySQL脏读幻读不可重复读及事务的隔离级别和MVCC、LBCC如何实现

mysql 直接拷贝data 目录下文件还原数据的如何实现

MySQL系列之十 MySQL事务隔离如何实现并发控制

mysql备份策略的如何实现(全量备份+增量备份)

MySql子查询IN的执行和优化的如何实现