# 查询结果分组 group
# 初始化数据
truncate table user;
insert into `user`(`user_code`, `user_name`, `age`, `money`) values("no1", "小明", 32, 1.2);
insert into `user`(`user_code`, `user_name`, `age`, `money`) values("no2", "小芳", 25, 5.2);
insert into `user`(`user_code`, `user_name`, `age`, `money`) values("no3", "小东", 32, 7.2);
insert into `user`(`user_code`, `user_name`, `age`, `money`) values("no4", "小宇", 25, 8.2);
insert into `user`(`user_code`, `user_name`, `age`, `money`) values("no5", "小灵", 21, 8.2);
# 按年龄区分那个年龄的人最有钱
select age, max(`money`) from `user` group by age
查询过程把所有数据按age分组,再每组取money字段最大的数据返回,其中max就是是聚合函数了 其它常见的聚合函数:min()取最小值,avg() 取平均数据, sum()求和等等
# 对分组返回的结果进行条件判断
select age, max(`money`) as maxmoney from `user` group by age having maxmoney > 8
查询结果中只返回8块已上的数据, 32岁的被过滤掉了
# 可以查询段既不是group字段也不是聚合结果的字段吗
select age, max(`money`) as maxmoney,id from `user` group by age having maxmoney > 8
返回了一个id字段,这个字段既不是group字段也不是聚合结果,在mysql中它是可以执行成功的。但是在其它类型的sql数据库中是不能这么执行的,而且这种sql语义也不清晰