mysql之行转列与列转行

mysql之行转列与列转行是数据查询的常见操做,以更好的来展现数据,下面就详细说说怎么实现。mysql

 

 

行转列sql

行转列的话,就是将一条一条的行数据记录转换为一条列数据展现,通常来讲是根据某一列来作汇总数据的操做,看着更直观,一目了然。
spa

  

建表语句:code

1 CREATE TABLE `st_grade` ( 2   `id` int(10) NOT NULL AUTO_INCREMENT, 3   `stu_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 4   `course` varchar(20) DEFAULT NULL, 5   `score` float(4,1) DEFAULT NULL, 6   PRIMARY KEY (`id`) 7 ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

 

插入数据:blog

1 INSERT INTO `st_grade` VALUES ('1', '张三', '语文', '86.0'); 2 INSERT INTO `st_grade` VALUES ('2', '张三', '数学', '90.0'); 3 INSERT INTO `st_grade` VALUES ('3', '张三', '英语', '75.0'); 4 INSERT INTO `st_grade` VALUES ('4', '李四', '语文', '92.0'); 5 INSERT INTO `st_grade` VALUES ('5', '李四', '数学', '93.0'); 6 INSERT INTO `st_grade` VALUES ('6', '李四', '英语', '96.0'); 7 INSERT INTO `st_grade` VALUES ('7', '王五', '语文', '82.0'); 8 INSERT INTO `st_grade` VALUES ('8', '王五', '数学', '71.0'); 9 INSERT INTO `st_grade` VALUES ('9', '王五', '英语', '74.0');

 

查询语句:ci

1 select stu_name , 2   max(case course when '语文' then score else 0 end ) 语文, 3   max(case course when '数学' then score else 0 end ) 数学, 4   max(case course when '英语' then score else 0 end ) 英语 5 from st_grade 6 group by stu_name;

 

列转行数学


列转行的话,就是将一条列数据转换为一条一条的行数据记录展现,将某一行数据根据某些列进行分组操做。
io

 

 建表语句:class

1 CREATE TABLE `st_grade` ( 2   `id` int(10) NOT NULL AUTO_INCREMENT, 3   `stu_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, 4   `course` varchar(20) DEFAULT NULL, 5   `score` float(4,1) DEFAULT NULL, 6   PRIMARY KEY (`id`) 7 ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

 

插入语句:select

1 INSERT INTO `st_grade` VALUES ('1', '张三', '语文', '86.0'); 2 INSERT INTO `st_grade` VALUES ('2', '张三', '数学', '90.0'); 3 INSERT INTO `st_grade` VALUES ('3', '张三', '英语', '75.0'); 4 INSERT INTO `st_grade` VALUES ('4', '李四', '语文', '92.0'); 5 INSERT INTO `st_grade` VALUES ('5', '李四', '数学', '93.0'); 6 INSERT INTO `st_grade` VALUES ('6', '李四', '英语', '96.0'); 7 INSERT INTO `st_grade` VALUES ('7', '王五', '语文', '82.0'); 8 INSERT INTO `st_grade` VALUES ('8', '王五', '数学', '71.0'); 9 INSERT INTO `st_grade` VALUES ('9', '王五', '英语', '74.0');

 

查询语句:

1 select stu_name, '语文' course , cn_score as score 2     from st_grade2 3     union select stu_name, '数学' course, math_score as score from st_grade2 4     union select stu_name, '英语' course, en_score as score from st_grade2 5 order by stu_name,course;

 

以上代码能够直接复制来验证,没有错误。

相关文章
相关标签/搜索