9.1 聚集函数
如果需要汇总数据而不用把它们实际检索出来,SQL提供了专门的函数。使用这些函数,SQL查询可用于检索数据,以便分析和报表生成。比如:
- 确定表中行数
- 获得表中某些行的和
- 找出表列的最大值、最小值、平均值
函数 | 说明 |
---|---|
AVG() | 返回某列的平均值 |
COUNT() | 返回某列的行数 |
MAX() | 返回某列的最大值 |
MIN() | 返回某列的最小值 |
SUM() | 返回某列值之和 |
AVG() 函数
AVG() 通过对表中行数计数并计算其列值之和,并求该列的平均值。它可以返回所有列的平均值,也可以返回特定列或行的平均值。
# 返回products表中所有产品的平均价格
select AVG(prod_price) as avg_price
from products;
# 返回products表中特定供应商的平均价格
select AVG(prod_price) as avg_price
from products
where vend_id = 'DLL01';
COUNT() 函数
COUNT() 用来计数,可利用其确定表中行的数目或符合特定条件的行的数目。
- 使用COUNT(*)对表中行的数目进行计数,不管表列中包含的是空值还是非空值。
- 使用COUNT(column)对特定列中具有值的行进行计数,忽略NULL值。
#返回customers表中顾客的总数
select count(*) as num_cust
from customers;
select count(cust_email) as num_cust
from customers;
MAX() 函数
MAX() 返回指定列中的最大值,要求指定列名,它忽略列值为NULL的行。
select MAX(prod_price) as max_price
from products;
MIN() 函数
与MAX() 功能相反,不再赘述。
SUM() 函数
SUM() 用来返回指定列值的和。
select SUM(quantity) as items_ordered
from orderItems
where order_num = 20005;
SUM() 也可以用来合计计算值。
select SUM(item_price * quantity) as items_ordered
from orderItems
where order_num = 20005;
9.2 聚集不同值
以上5个聚集函数都可以如下使用
- 对所有行执行计算,指定ALL参数或不指定(默认ALL)
- 只包含不同的值,指定DISTINCT参数。
# 平均值只考虑各个不同的价格
select AVG(DISTINCT prod_price) as avg_price
from products
where vend_id = 'DLL01';
【注意】如果指定列名,DISTINCT只能用于COUNT(),不能用于COUNT(*)。
9.3 组合聚集函数
select可以根据需要包含多个聚集函数
select count(*) as num_items,
MIN(prod_price) as price_min,
MAX(prod_price) as price_max,
AVG(prod_price) as price_avg
from products;