Aggregate data-aggregate function

1. Aggregate function

We often need to summarize data without actually retrieving them. To facilitate this type of retrieval, MySQL provides five aggregate functions, as follows:
Insert picture description here


1.1 AVG() function

Insert picture description here
Insert picture description here
The avg() function ignores rows whose column value is null.


1.2 count() function

The count() function counts, there are two ways to use it:

1.count(*) counts the number of rows in the table, regardless of whether the table column contains a null value (null) or a non-null value.
2. count(column) counts the rows with values ​​in a specific column, ignoring
null values.
Insert picture description here
Insert picture description here


1.3 max() function

Insert picture description here
The max() function ignores rows whose column value is null.


1.4 min() function

Insert picture description here
The min() function ignores rows whose column value is null.


1.5 sum() function

Insert picture description here
Insert picture description here
The sum() function ignores rows whose column value is null.


2. Gather different values

Insert picture description here


3. Combining aggregate functions

Insert picture description here


-- AVG()函数
SELECT AVG(prod_price) AS avg_price FROM products;

-- AVG()函数,确定特定列的值
SELECT AVG(prod_price) AS avg_price FROM products WHERE vend_id = 1003;

-- count(*)函数,对所有行计数
SELECT COUNT(*) AS num_cust FROM customers;

-- count(列名),只对列中有值的进行计数,不包含null值
SELECT COUNT(cust_email) AS num_cust FROM customers;

-- max()函数
SELECT MAX(prod_price) AS max_price FROM products;

-- min()函数
SELECT MIN(prod_price) AS min_price FROM products;

-- sum()函数
SELECT SUM(quantity) AS items_ordered FROM orderitems WHERE order_num = 20005;

-- SUM()也可以用来合计计算值
SELECT SUM(item_price*quantity) AS total_price FROM orderitems WHERE order_num = 20005;

-- distinct()函数,只包含不同的值
SELECT AVG(DISTINCT prod_price) AS avg_price FROM products WHERE vend_id = 1003;

-- 组合聚集函数,多个聚集函数组成
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;

Guess you like

Origin blog.csdn.net/weixin_49984044/article/details/108689793