聚合函数
Count()计数
(1)统计一个班多少学生
select count(id) from student;
select count(*) from student;
(2)统计ui分数大于60的学生个数
select count(*) from score where ui>60;
统计总分大于200的人数
select count(*) from score where (python+ui+mysql)>200;
Sum() 求和
(1)统计一个班mysql总成绩
select sum(mysql) from score;
(2)统计各科的总成绩
select sum(python),sum(mysql),sum(ui) from score;
(3)统计python,mysql,ui总成绩之和
select sum(python+mysql+ui) from score;
(4)统计一个班python成绩的平均分
select avg(python) from score;
select sum(python)/count(python) from score;
Avg() 求平均数
select avg(python+mysql+ui) from score;
min()求最小,max()求最大
select min(ui),max(ui) from score;
求每个学生的平均分
select name,(python+ui+mysql)/3 FROM score;
group by 分组。
GROUP BY子句的真正作用在于与各种聚合函数配合使用。它用来对查询出来的数据进行分组。
create table t_order(id int primary key,product varchar(20),price float(8,2));
insert into t_order values(1,'xiaomi', 1000);
insert into t_order values(2,'xiaomi',1100);
insert into t_order values(3,'huawei',2200);
insert into t_order values(4,'apple',8200);
1.对订单表中商品归类后,显示每一类商品的总价
select product,sum(price) from t_order GROUP BY product;
2.查询每一类商品总价格大于3000的商品
select product,sum(price) as total from t_order GROUP BY product HAVING total>3000;
WHERE是在分组(group by)前进行条件过滤,
HAVING子句是在分组(group by)后进行条件过滤,
WHERE子句中不能使用聚合函数,HAVING子句可以使用聚合函数。