1、聚集函数:对行运行的函数,计算并返回一个值。
avg()返回一列的平均值
count()返回一列的行数
max()返回一列的最大值
min()返回一列的最小值
sum()返回一列的总和值
1、1avg()
例子:返回products表中所有产品的平均价格
select avg(prod_price) as avg_price from products /* avg_price 6.823333 */
例子:返回DLL01供应商的产品的平均价格(行)
select avg(prod_price) as avg_price from products where vend_id = ‘DLL01‘; /* avg_price 3.865000 */
1、2count()函数
例子:customers表中用户总数(行数)
select count(*) as num_cust from customers; /* num_cust 5 */
例子:具有电子邮箱地址的用户数
select count(cust_email) as num_cust from customers; /* num_cust 3 */
注意:如果指定列名,则count()函数会忽略NULL,如是*则不会忽略。
1、3max()函数
例子:返回表中最贵的物品的价格
select max(prod_price) as max_price from products; /* max_price 11.99 */
1、4min()函数
例子:返回表中最便宜的物品的价格
select min(prod_price) as min_price from products; /* min_price 3.49 */
1、5sum()函数
例子:orderitems表中物品总数(quantity值这和)
select sum(quantity) as items_ordered from orderitems where order_num = 20005; /* items_ordered 200 */
例子:返回物品总价值
select sum(quantity*item_price) as total_price from orderitems where order_num = 20005; /* total_price 1648.00 */
2、聚集不同值
以上5个聚集函数都可以加参数
ALL参数(默认)或无参数对所有行执行计算
DISTINCT参数,只包含不同的值,不能用于count(*)中
例子:不同价格的平均值
select avg(distinct prod_price) as avg_price from products where vend_id = ‘DLL01‘; /* avg_price 4.240000 */
3、组合聚集函数
select count(*) as num_items, min(prod_price) as price_min, max(prod_price) as price_max, avg(prod_price) as price_avg, sum(prod_price) as price_sum from products; /* num_items price_min price_max price_avg price_sum 9 3.49 11.99 6.823333 61.41 */
时间: 2024-10-12 01:58:10