目录
学生成绩表的设计,学生、课程、分数。但有时候页面看数据就想清楚看到一个人的成绩,此类需求工作中,尤其是报表同事还是挺常见的,此类问题被称为“行转列”。此处提供两种实现方式case-when、join。
学生表
CREATE TABLE `score` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`s_name` varchar(45) DEFAULT NULL,
`course` varchar(45) DEFAULT NULL,
`score` tinyint(4) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COMMENT='学生成绩';
INSERT INTO `score` VALUES (1,'bao','语文',88),(2,'bao','数学',99),(3,'bao','英语',90),(4,'erbao','语文',93),(5,'erbao','数学',92),(6,'erbao','英语',86);
如图:
case-when实现:
-- case when
select s_name,
max(case
when course='语文' then score
else 0
end) as 语文,
max(case
when course='数学' then score
else 0
end) as 数学,
max(case
when course='英语' then score
else 0
end) as 英语
from score
group by s_name
join
-- join
select s1.s_name, s1.语文, s2.数学,s3.英语 from
(select s_name, score as 语文 from score where course='语文') s1 join
(select s_name, score as 数学 from score where course='数学') s2 on s1.s_name=s2.s_name join
(select s_name, score as 英语 from score where course='英语') s3 on s2.s_name=s3.s_name