mysql经典问题之group by和max函数

原表为:type=科目,score=成绩

CREATE TABLE `order_test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `type` varchar(255) DEFAULT NULL,
  `score` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
INSERT INTO `test`.`order_test` (`id`, `name`, `type`, `score`) VALUES ('1', '张三', 'a', '67');
INSERT INTO `test`.`order_test` (`id`, `name`, `type`, `score`) VALUES ('2', '李四', 'a', '20');
INSERT INTO `test`.`order_test` (`id`, `name`, `type`, `score`) VALUES ('3', '王五', 'a', '63');
INSERT INTO `test`.`order_test` (`id`, `name`, `type`, `score`) VALUES ('4', '张三', 'b', '88');
INSERT INTO `test`.`order_test` (`id`, `name`, `type`, `score`) VALUES ('5', '李四', 'b', '78');
INSERT INTO `test`.`order_test` (`id`, `name`, `type`, `score`) VALUES ('6', '王五', 'b', '68');
INSERT INTO `test`.`order_test` (`id`, `name`, `type`, `score`) VALUES ('7', '张三', 'c', '70');
INSERT INTO `test`.`order_test` (`id`, `name`, `type`, `score`) VALUES ('8', '李四', 'c', '80');
INSERT INTO `test`.`order_test` (`id`, `name`, `type`, `score`) VALUES ('9', '王五', 'c', '100');

 题目:查出每个科目成绩最高的人

如果这样使用select name,type,max(score) from order_test GROUP BY type   (mysql这么写是合规的,不需要将group by和前面select的字段全部匹配,为了展示这一现象,也不能匹配,否则这个现象体现不出来!)

结果为:

发现第三条数据和原来的数据不一致。

这时就要了解一个特性,group by分组后,则返回的是第一条记录的基本信息的特性

就是因为这一特性导致我们查的数据不一致,需要对原sql进行修改,排序后再查,这样第一条数据就是我们需要的。

修改后sql:先子查询order by,再外层用group by

扫描二维码关注公众号,回复: 11621666 查看本文章

select name,type,MAX(score) from (select * from order_test order by score desc) as a GROUP BY type

后记:目前没有oracle环境,也很久没用过oracle了,比如oracle要按科目分组,但select要展示十几个字段,那如何写sql? 

猜你喜欢

转载自blog.csdn.net/qq_39404258/article/details/105951309