04-聚合函数

为了快速得到统计数据,经常会用到如下5个聚合函数

1.总数:count()

count(*)表示计算总行数,括号中写星与列名,结果是相同的     

例1:查询学生总数
select count(*) from students;    

注意:    
    count(*)、count(1):会统计所有记录
    count(列名):不会统计指定列为NULL的记录,注意NULL和""不一样  

2.最大值:max()

max(列)表示求此列的最大值 

例2:查询女生的编号最大值
select max(id) from students where gender=2;   

3.最小值:min()

min(列)表示求此列的最小值  

例3:查询未删除的学生最小编号
select min(id) from students where is_delete=0;  

4.求和:sum()

sum(列)表示求此列的和 

例4:查询男生的总年龄
select sum(age) from students where gender=1;

和count()结合算出平均年龄
select sum(age)/count(*) from students where gender=1;  

5.平均值:avg()

avg(列)表示求此列的平均值

例5:查询未删除女生的编号平均值
select avg(id) from students where is_delete=0 and gender=2;

Last updated

Was this helpful?