以下内容是学习《mysql必知必会》中的函数
汇总数据
一、AVG()函数,计算当前列的平均值
——括号中指定要计算的列,AS后面为将结果列命名为什么
——若需要多个列的平均值,需要多个AVG函数
——会忽略列值为NULL的行
select AVG(amount) as avg_amount from deposite;
//——算出amount的平均值,并把显示的列定义为avg_amount
select AVG(amount) as avg_amount from deposite where b_id='B0002';
//搜索出b_id为B0002的人的存款并且计算平均值
二、Count()函数——计数
count(*)——对表中行的数目进行计数,包括为空值(NULL)
select count(*) as num_cust from customer;
count(column)对特定列中具有值的行进行计数,忽略null值
select count(location) as num_cust from customer;
//——location这一列为空的人,则不会被统计进来
三、MAX()和MIN()——最大值和最小值
MAX()函数,返回指定列中的最大值,必须指定列名,忽略值为NULL的行
select max(amount) as max_am from deposite;
MIN()函数,返回指定列中的最小值,需要指定列名,忽略值为NULL的行
select min(amount) as min_am from deposite;
四、SUM()函数——返回指定列值的和(总计)
select sum(amount) as sum_am from deposite where b_id='B0001';
select sum(amount*salary) as sum from deposite, customer;
筛选不同的数:DISTINCT
select AVG(DISTINCT c_id) from deposite;//——去掉了重复的值
select AVG(c_id) from deposite;
*如果指定列明,只能用count(),不能用于count(*)——即count(distinct)是错误的
五、组合聚集函数
select
count(*) as num_people, //统计表中的行数
min(c_id) as min_id,
max(c_id) as max_id,
avg(amount) as avg_amount
from deposite;
分组数据
一、创建分组
select b_id,count(*) as num from deposite group by b_id;
//统计表的行数,并且根据b_id来进行分组统计对应的数量
二、过滤分组
1、HAVING ——根据分组来进行过滤
select b_id,count(*) as num from deposite group by b_id having count(*)>=4;
2、where 和 having 组合过滤
select b_id,count(*) as num from deposite
where amount>60000 group by b_id having count(*)>1;
//搜出amount大于60000,并根据b_id进行分组
三、分组和排序
遵守规则:
select——返回的列或表达式 from——要从中检索数据的表 where——按行过滤
group by——分组说明 having——按组过滤 order by——输出排序顺序
limit——要检索的行数