MySQL data grouping

SQL aggregate functions can be used to summarize data, which allows us to obtain average, maximum and minimum values ​​without having to retrieve all the data. So far, all calculations have been performed on all data in the table that matches a specific WHERE clause. Let us first look at a table

What if we want to get the sum of the products provided by each supplier? 

This requires the use of grouping, which allows data to be divided into multiple logical groups in order to aggregate calculations for each group

 

 1. GROUP BY-create a group

The grouping is established in the GROUP BY clause of the SELECT statement.

Following the above example, calculate the total price of goods provided by each supplier. At this time, it is necessary to group by supplier id, and then use the aggregate function SUM () to find the total price of each supplier's goods.

SELECT supply,SUM(price) AS price_sum FROM product GROUP BY supply

The GROUP BY clause instructs MySQL to group data and then aggregate each group

If the grouping column has a NULL value, it will also be divided into a group, the GROUP BY clause must be after the WHERE clause, before the ORDER BY clause

 

 

 2. HAVING-filter grouping

 

Published 138 original articles · praised 34 · 150,000 views

Guess you like

Origin blog.csdn.net/bbj12345678/article/details/105513557