第一步:建立学生表、课程表、分数表并插入数据:
CREATE TABLE `a_student` (
`stuid` VARCHAR(10) NOT NULL COMMENT '学号',
`stunm` VARCHAR(20) NOT NULL COMMENT '姓名',
PRIMARY KEY (`stuid`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `a_subject` (
`courseno` VARCHAR(20) NOT NULL,
`coursenm` VARCHAR(20) NOT NULL,
PRIMARY KEY (`courseno`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COMMENT='课程';
CREATE TABLE `a_score` (
`stuid` VARCHAR(16) NOT NULL,
`courseno` VARCHAR(20) NOT NULL,
`scores` FLOAT DEFAULT NULL,
PRIMARY KEY (`stuid`,`courseno`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COMMENT='分数';
INSERT INTO `a_student` VALUES ('S001', '张三');
INSERT INTO `a_student` VALUES ('S002', '李四');
INSERT INTO `a_student` VALUES ('S003', '王五');
INSERT INTO `a_subject` VALUES ('C001', '英语');
INSERT INTO `a_subject` VALUES ('C002', '数学(一)');
INSERT INTO `a_subject` VALUES ('C003', '软件工程');
INSERT INTO `a_subject` VALUES ('C004', '计算机科学与技术');
INSERT INTO `a_score` VALUES ('S001', 'C001', '69');
INSERT INTO `a_score` VALUES ('S001', 'C002', '65');
INSERT INTO `a_score` VALUES ('S001', 'C003', '99');
INSERT INTO `a_score` VALUES ('S002', 'C001', '98');
INSERT INTO `a_score` VALUES ('S002', 'C002', '56');
INSERT INTO `a_score` VALUES ('S002', 'C003', '90');
INSERT INTO `a_score` VALUES ('S003', 'C001', '69');
INSERT INTO `a_score` VALUES ('S003', 'C002', '89');
INSERT INTO `a_score` VALUES ('S003', 'C003', '85');
INSERT INTO `a_score` VALUES ('S003', 'C004', '105');
第二步:进行关联查询:
SELECT b.stunm,c.coursenm, a.scores
FROM `a_score` a
INNER JOIN `a_student` b
INNER JOIN `a_subject` c
ON
a.stuid = b.stuid
AND
a.courseno = c.courseno
效果:
第三步:行转列查询:
SELECT
a.stuid 编号,
a.stunm 姓名,
MAX(
CASE c.coursenm
WHEN '英语' THEN
s.scores
ELSE
0
END
) '英语',
MAX(
CASE c.coursenm
WHEN '数学(一)' THEN
s.scores
ELSE
0
END
) '数学(一)',
MAX(
CASE c.coursenm
WHEN '软件工程' THEN
s.scores
ELSE
0
END
) '软件工程',
MAX(
CASE c.coursenm
WHEN '计算机科学与技术' THEN
s.scores
ELSE
0
END
) '计算机科学与技术'
FROM a_student a
INNER JOIN a_score s ON a.stuid = s.stuid
INNER JOIN a_subject c ON c.courseno = s.courseno
GROUP BY a.stuid
效果:
分析
1、CASE枚举所有课程作为行来展示;
2、根据学号来分组,用MAX()取最大值可以取到对应的值,避免取到第一行的值。