需求:有两张表,学生表(student)、成绩表(score),需要查询出每一个学生的平均成绩。
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) COLLATE utf8mb4_bin DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
INSERT INTO `MachineDb`.`student` (`name`) VALUES ('job');
INSERT INTO `MachineDb`.`student` (`name`) VALUES ('addy');
INSERT INTO `MachineDb`.`student` (`name`) VALUES ('barton');
INSERT INTO `MachineDb`.`student` (`name`) VALUES ('bab');
INSERT INTO `MachineDb`.`student` (`name`) VALUES ('stive');
INSERT INTO `MachineDb`.`student` (`name`) VALUES ('mout');
CREATE TABLE `score` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`studentId` int(11) DEFAULT NULL,
`mark` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
INSERT INTO `MachineDb`.`score` (`studentId`, `mark`) VALUES ('1', '1');
INSERT INTO `MachineDb`.`score` (`studentId`, `mark`) VALUES ('1', '2');
INSERT INTO `MachineDb`.`score` (`studentId`, `mark`) VALUES ('1', '3');
INSERT INTO `MachineDb`.`score` (`studentId`, `mark`) VALUES ('1', '4');
INSERT INTO `MachineDb`.`score` (`studentId`, `mark`) VALUES ('1', '5');
INSERT INTO `MachineDb`.`score` (`studentId`, `mark`) VALUES ('1', '6');
INSERT INTO `MachineDb`.`score` (`studentId`, `mark`) VALUES ('1', '7');
INSERT INTO `MachineDb`.`score` (`studentId`, `mark`) VALUES ('1', '8');
INSERT INTO `MachineDb`.`score` (`studentId`, `mark`) VALUES ('1', '9');
INSERT INTO `MachineDb`.`score` (`studentId`, `mark`) VALUES ('2', '66');
查询平均成绩
select studentId ,CAST(AVG(mark) AS DECIMAL(10,2)) AS avgMark from score group by studentId
平均成绩放进临时表
create temporary table t(
select studentId ,CAST(AVG(mark) AS DECIMAL(10,2)) AS avgMark from score group by studentId
);
查询学生的平均成绩
select id , name ,t.avgMark from student s
left join t on s.id=t.studentId
结果大概如下所示
id | name | avgMark |
---|---|---|
1 | job | 5.00 |
欢迎讨论