查询每个学期每门课程最高分记录

建表的sql语句:

DROP TABLE IF EXISTS `grade1`;
CREATE TABLE `grade1` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(4) DEFAULT NULL,
  `course` varchar(4) DEFAULT NULL,
  `score` int(5) DEFAULT NULL,
  `year` int(4) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

INSERT INTO `grade1` VALUES ('1', '张三', '语文', '10', '2015');
INSERT INTO `grade1` VALUES ('2', '张三', '语文', '20', '2016');
INSERT INTO `grade1` VALUES ('3', '张三', '数学', '10', '2015');
INSERT INTO `grade1` VALUES ('4', '张三', '数学', '5', '2016');
INSERT INTO `grade1` VALUES ('5', '李四', '数学', '10', '2015');
INSERT INTO `grade1` VALUES ('6', '李四', '数学', '20', '2016');
INSERT INTO `grade1` VALUES ('7', '李四', '语文', '10', '2015');
INSERT INTO `grade1` VALUES ('8', '李四', '语文', '5', '2016');
INSERT INTO `grade1` VALUES ('9', '李四', '语文', '10', '2018');

sql语句:

select a.* from grade1 a join (select course,year,max(score) maxScore from grade1 group by year,course) b on a.year = b.year and a.course = b.course and  a.score = b.maxScore;

结果:

查询每个学期每门课程最高分记录_第1张图片

你可能感兴趣的:(java学习之路)