# 横表CREATE TABLE `table_h2z` (`name` varchar(32) DEFAULT NULL,`chinese` int(11) DEFAULT NULL,`math` int(11) DEFAULT NULL,`english` int(11) DEFAULT NULL) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;/*Data for the table `table_h2z` */insertinto `table_h2z`(`name`,`chinese`,`math`,`english`) values ('mike',45,43,87),('lily',53,64,88),('lucy',57,75,75);# 纵表CREATE TABLE `table_z2h` (`name` varchar(32) DEFAULT NULL,`subject` varchar(8) NOT NULL DEFAULT '',`score` int(11) DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;/*Data for the table `table_z2h` */insertinto `table_z2h`(`name`,`subject`,`score`) values ('mike','chinese',45),('lily','chinese',53),('lucy','chinese',57),('mike','math',43),('lily','math',64),('lucy','math',75),('mike','english',87),('lily','english',88),('lucy','english',75);
横表转纵表SELECT NAME, 'chinese' AS `subject`,chinese AS `score` FROM table_h2zUNION ALLSELECT NAME, 'math' AS `subject`,math AS `score` FROM table_h2zUNION ALLSELECT NAME, 'english' AS `subject`, english AS `score` FROM table_h2z
执行结果
+------+---------+-------+| name | subject | score |+------+---------+-------+| mike | chinese |45 || lily | chinese |53 || lucy | chinese |57 || mike | math|43 || lily | math|64 || lucy | math|75 || mike | english |87 || lily | english |88 || lucy | english |75 |+------+---------+-------+9 rows in set (0.00 sec)
纵表转横表SELECT NAME, SUM(CASE `subject` WHEN 'chinese' THEN score ELSE 0 END) AS chinese, SUM(CASE `subject` WHEN 'math' THEN score ELSE 0 END) AS math, SUM(CASE `subject` WHEN 'english' THEN score ELSE 0 END) AS englishFROM table_z2hGROUP BY NAME
执行结果
+------+---------+------+---------+| name | chinese | math | english |+------+---------+------+---------+| lily |53 |64 |88 || lucy |57 |75 |75 || mike |45 |43 |87 |+------+---------+------+---------+3 rows in set (0.00 sec)
作者:Sicimike
原文链接:https://blog.csdn.net/Baisitao_/article/details/104714764
【零散的MySQL基础总是记不住?看这一篇如何拯救你】
推荐阅读
- 什么是DNS?
- WEB渗透——MySQL注入原理与注入检测
- 林黛玉和史湘云的关系
- 中国历史细思极恐的细节
- 冬季锻炼时间的选择
- 姜子牙辅佐的是周文王吗 姜子牙辅佐的是周文王吗
- 腰部肌肉运动的锻炼方法
- 夏天锻炼肌肉的重点
- 每天锻炼肌肉的最佳时间
- 黑苦荞茶的功效与作用,黑苦荞茶的价格