SELECT AVG(prod_price) AS avg_price FROM products; #AVG只能用于单个列求平均值,如想计算多个列,必须用多个AVG() SELECT AVG(prod_price) AS avg_price FROM products WHERE vend_id = 1003; #AVG函数忽略列值为NULL的行 SELECT COUNT(*) AS num_cust FROM customers; #此时不忽略列为NULL的行 SELECT COUNT(cust_email) AS num_cust FROM customers; #此时忽略列为NULL的行 SELECT MAX(prod_price) AS max_price FROM products; #忽略列为NULL的行 SELECT MIN(prod_price) AS max_price FROM products; #忽略列为NULL的行 SELECT SUM(quantity) AS items_ordered FROM orderitems WHERE order_num = 20005; SELECT SUM(item_price*quantity) AS total_price FROM orderitems WHERE order_num = 20005; #忽略列值为NULL的行 SELECT AVG(DISTINCT prod_price) AS avg_price FROM products # 以上5个聚集函数,默认是对所有的行进行计算(ALL), WHERE vend_id = 1003; #如果只包含不同的值,可在列名前指定DISTINCT,但DISTINCT不能用于COUNT(*)。 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;
MySQL常用的聚集函数如下表,另外MySQL还支持一系列的标准偏差聚集函数: