mysql行转列和列转行实例详解 爱问知识人
mysql行转列、列转行语句不难,不做多余解释了,看语句时,从内往外一句一句剖析行转列有如图所示的表,现在希望查询的结果将行转成列建表语句如下:CREATE TABLE `TEST_TB_GRADE` ( `ID` int(10) NOT NULL AUTO_INCREMENT, `USER_NAME` varchar(20) DEFAULT NULL, `COURSE` varchar(20) DEFAULT NULL, `SCORE` float DEFAULT '0', PRIMARY KEY (`ID`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;insert into TEST_TB_GRADE(USER_NAME, COURSE, SCORE) values("张三", "数学", 34),("张三", "语文", 58),("张三", "英语", 58),("李四", "数学", 45),("李四", "语文", 87),("李四", "英语", 45),("王五", "数学", 76),("王五", "语文", 34),("王五", "英语", 89);查询语句:此处用之所以用MAX是为了将无数据的点设为0,防止出现NULLSELECT user_name , MAX(CASE course WHEN '数学' THEN score ELSE 0 END ) 数学, MAX(CASE course WHEN '语文' THEN score ELSE 0 END ) 语文, MAX(CASE course WHEN '英语' THEN score ELSE 0 END ) 英语FROM test_tb_gradeGROUP BY USER_NAME;结果展示:列转行有如图所示的表,现在希望查询的结果将列成行建表语句如下:CREATE TABLE `TEST_TB_GRADE2` ( `ID` int(10) NOT NULL AUTO_INCREMENT, `USER_NAME` varchar(20) DEFAULT NULL, `CN_SCORE` float DEFAULT NULL, `MATH_SCORE` float DEFAULT NULL, `EN_SCORE` float DEFAULT '0', PRIMARY KEY (`ID`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;insert into TEST_TB_GRADE2(USER_NAME, CN_SCORE, MATH_SCORE, EN_SCORE) values("张三", 34, 58, 58),("李四", 45, 87, 45),("王五", 76, 34, 89);查询语句:select user_name, '语文' COURSE , CN_SCORE as SCORE from test_tb_grade2union select user_name, '数学' COURSE, MATH_SCORE as SCORE from test_tb_grade2union select user_name, '英语' COURSE, EN_SCORE as SCORE from test_tb_grade2order by user_name,COURSE;结果展示:感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!您可能感兴趣的文章:
sql语句实现行转列的3种方法实例SQLServer行转列实现思路记录MySQL存储过程中使用动态行转列mssql 数据库表行转列,列转行终极方案Sql Server 2000 行转列的实现(横排)SQL查询语句行转列横向显示实例解析sql动态行转列的两种方法table 行转列的sql详解SQL行转列和列转行代码详解SQL基础教程之行转列Pivot函数。