聚合函数
AVG:求某一列平均值
COUNT:统计总行数
SUM:计算列总和
MIN:求某一列的最小值
MAX:求某一列的最大值
AVG:求某一列平均值
SELECT AVG(age) FROM studentinfo;
求某一列值(起一个别名)
SELECT AVG(age) as avgage FROM studentinfo;
SELECT MIN(age) as minage FROM studentinfo;
SELECT MAX(age) as maxage FROM studentinfo;
SELECT SUM(age) FROM studentinfo;
SELECT COUNT(*) FROM studentinfo;
DISTINCT去重,只计算不同的值
SELECT SUM(DISTINCT age) FROM studentinfo;
添加条件,进行聚合函数的计算
SELECT COUNT(gender) FROM studentinfo WHERE gender=1;
SELECT COUNT(gender) FROM studentinfo WHERE gender=0;
分组跟聚合函数的使用,统计每一个分组下有多少人(有多少条记录)
SELECT count(*) as total,age FROM studentinfo GROUP BY age;
统计分组的信息
SELECT count(*), avg(age),min(age),sum(age),gender FROM studentinfo GROUP BY gende;
group by 与 group_concat(列)
group_concat(字段名)可以作为一个输出字段来使用,
表示分组之后,根据分组结果,使用group_concat()来放置每一组的某字段的值的集合
SELECT gender,group_concat(student_name),group_concat(age) FROM studentinfo GROUP BY gender;
group by + with rollup
在最后新增一行,来记录当前列里所有记录的总和
SELECT gender,count(*) FROM studentinfo GROUP BY gender with rollup;
HAVING
HAVING非常类似于WHERE
唯一的差别是WHERE过滤行,而HAVING过滤分组
having 条件表达式:用来分组查询后指定一些条件来输出查询结果
having作用和where类似,但having只能用于group by
SELECT COUNT(),age,adress FROM customers GROUP BY age,adress HAVING COUNT() >= 2;