MySQL row-specific columns (student grades)

Table of contents

case-when implementation:

 join


        Design of student report card, student, course, score. But sometimes when looking at the data on the page, you want to see a person's achievements clearly. This kind of demanding work, especially for reporting colleagues, is quite common. This kind of problem is called "row-to-column". Two implementation methods case-when and join are provided here.

student form

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);

As shown in the picture:

case-when implementation:

-- 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

Guess you like

Origin blog.csdn.net/u011471105/article/details/124654789
Recommended