行转列
CREATE TABLE `score` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(40) COLLATE utf8mb4_bin DEFAULT NULL,
`subject` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,
`score` int(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
BEGIN;
INSERT INTO `score` VALUES (1, '张三', '语文', 80);
INSERT INTO `score` VALUES (2, '张三', '数学', 85);
INSERT INTO `score` VALUES (3, '张三', '英语', 90);
INSERT INTO `score` VALUES (4, '李四', '语文', 60);
INSERT INTO `score` VALUES (5, '李四', '数学', 50);
INSERT INTO `score` VALUES (6, '李四', '英语', 70);
COMMIT;
select NAME,
MAX(CASE SUBJECT WHEN '语文' then score end ) '语文',
MAX(CASE SUBJECT WHEN '数学' THEN score END) '数学',
MAX(CASE SUBJECT WHEN '英语' THEN score END) '英语'
from score GROUP BY NAME
- 结果
列转行
CREATE TABLE `score2` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,
`yw_score` int(5) DEFAULT NULL,
`sx_score` int(5) DEFAULT NULL,
`yy_score` int(5) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
BEGIN;
INSERT INTO `score2` VALUES (1, '张三', 80, 90, 85);
INSERT INTO `score2` VALUES (2, '李四', 70, 50, 80);
COMMIT;
set @num:=0;
select @num
select @num:=@num +1 'id', NAME, '语文' as 'subject', yw_score as SCORE from score2
UNION
select @num:=@num +1 'id', NAME, '数学' as 'subject', sx_score as SCORE from score2
UNION
select @num:=@num +1 'id', NAME ,'英语' as 'subject', yy_score as SCORE from score2