1 前言 {#1-%E5%89%8D%E8%A8%80}
表结构如下: (主键、学生名、课程科目、成绩)
行转列处理后的结果:
最终仪表板视图效果:
2 详细步骤 {#2-%E8%AF%A6%E7%BB%86%E6%AD%A5%E9%AA%A4}
2.1 建表,导入数据 {#2.1-%E5%BB%BA%E8%A1%A8%EF%BC%8C%E5%AF%BC%E5%85%A5%E6%95%B0%E6%8D%AE}
-- 建表语句:
DROP TABLE IF EXISTS `student_score`;
CREATE TABLE `student_score` (
`id` int(8) NOT NULL,
`name` varchar(20) DEFAULT NULL,
`project` varchar(20) DEFAULT NULL,
`score` int(8) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
`/*Data for the table ``student_score`` */
insert into ``student_score``(``id``,``name``,``project``,``score``) values
(1,'张三','语文',80),
(2,'张三','数学',70),
(3,'张三','英语',90),
(4,'张三','物理',60),
(5,'李四','语文',95),
(6,'李四','数学',96),
(7,'李四','英语',97),
(8,'李四','物理',99),
(9,'王五','语文',100),
(10,'王五','英语',100);
`
2.2 生成行转列 sql {#2.2-%E7%94%9F%E6%88%90%E8%A1%8C%E8%BD%AC%E5%88%97-sql}
-- 实现语句(不需要存储过程)
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'Max(IF(a.project = ''',
a.project,
''', a.score, 0)) AS ''',
a.project, ''''
)
) INTO @sql
FROM student_score a;
SET @sql = CONCAT('Select name,', @sql,
' From student_score a Group by a.name' );
-- 动态生成脚本
PREPARE stmt FROM @sql;
-- 动态执行脚本
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
`-- 查询生成的行转列sql
select @sql;
`