三、常用函数
首先创建一个这样的表格:
1.1聚合函数
1.count() :求满足列条件的总的行数。
练习:
(1)、统计一个班级共有多少学生?
select count(id) from student_score;
select count(python) from score;-- 会忽略空的结果
SELECT COUNT(*) FROM student;
(2)、统计总分大于250的人数有多少?
select count(*) from score where(python+ui+mysql)>250;或者
select * from score where(python+ui+mysql)>250;
(3)统计python成绩大于80的
select count(*) from score where python>80;
注意: 除了COUNT(*)以外,其他字段都会忽略NULL值;
sum(): 求总和。
(1)、统计一个班级python总成绩?
select sum(python) from score;
(2)求各科的总成绩:
select sum(python),sum(ui),sum(mysql) from score;
(3)求python成绩的平均分:
select AVG(python) from score;-- 第一种方法
select sum(python)/count(*) from score;-- 第二种方法
3.avg(): 求平均数。
求一个班级总分平均分
select avg(python+ui+mysql) from score;
4.min() 和 max() 求最大值和最小值。
求python中的最高成绩和最低成绩:
select max(python),min(python) from score;
5.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) FROM t_order GROUP BY product HAVING SUM(price)>100;
注意:
(1)、分组函数的重要规则
如果使用了分组函数,或者使用GROUP BY 的查询:出现在SELECT列表 中的字段,要么出现在聚合函数里,要么出现在GROUP BY 子句中。
(上面的product出现在了group by中,price出现在了聚合函数中)
GROUP BY 子句的字段可以不出现在SELECT列表当中。
(2)、having where 的区别
①、where和having都是用来做条件限定的,
②、WHERE是在分组(group by)前进行条件过滤,
③、HAVING子句是在分组(group by)后进行条件过滤,
④、WHERE子句中不能使用聚合函数,HAVING子句可以使用聚合函数。
⑤、HAVING子句用来对分组后的结果再进行条件过滤
having sum(price)>2000 相当于 拿着 列名为sum(price)去查询。