实例如下:
update users set classes='1' where id in('u001','u002','u003','u004');
update users set classes='2' where id in('u005','u006','u007');
users表的内容如下:
+------+-----------+------------+------+-------+---------+
| id | firstname | secondname | age | count | classes |
+------+-----------+------------+------+-------+---------+
| u001 | 张 | 飞 | 18 | 60 | 1 |
| u002 | 赵 | 云 | 20 | 58 | 1 |
| u003 | 关 | 羽 | 22 | 80 | 1 |
| u004 | 刘 | 备 | 25 | 98 | 1 |
| u006 | 黄 | 盖 | 18 | NULL | 2 |
| u005 | 王 | 子云 | 12 | 20 | 2 |
| u007 | 诸葛 | 亮 | 24 | 100 | 2 |
+------+-----------+------------+------+-------+---------+
查询1班和2班的平均成绩:
select avg(count) from users group by classes;
会计算null值的。
select sum(count) from users group by classes;//各组count总和
select count(*) from users group by classes;//各组人员个数
select sum(count)/count(*) as avg from users group by classes;//各组count平均值
查询班级平均成绩不及格的班级详细人员信息
select sum(count)/count(*) as avg from users group by classes;
select classes,sum(count)/count(*) as avg from users group by classes;->temp
(select classes,sum(count)/count(*) as avg from users group by classes)as temp
//查出班级的平均分数小于60的组 和平均分。
select classes,sum(count)/count(*) as avg from users group by classes having avg<60;-temp
select * from users,
(select classes,sum(count)/count(*) as avg from users group by classes having avg<60)as temp
where users.classes=temp.classes;
//having 子句的作用。
出现其它数据项,语法上,不会直接报错,但是没有任何意义。
3.对于having子句,只用于分组,是对分组查询结果进行条件限制的。
也就是说在这个例子中,having子句中只能出现对classes的限定和聚合函数的值的限定。
原文链接:https://www.f2er.com/javaschema/285562.html