1 前言
表结构如下: (主键、学生名、课程科目、成绩)
行转列处理后的结果:
最终仪表板视图效果:
2 详细步骤
2.1 建表,导入数据
-- 建表语句:
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
-- 实现语句(不需要存储过程)
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;