MySQL basics: group group by

Author: Dian ordinary world 

Source: SQL database development

The mysql basic knowledge series has new knowledge points. Today I want to introduce you to the grouping GROUP BY.

GROUP BY function

The GROUP BY statement is used in combination with aggregate functions to group the result set based on one or more columns.

GROUP BY syntax

SELECT column_name, 

aggregate_function(column_name)

FROM table_name

WHERE column_name operator value

GROUP BY column_name;

Sample data sheet

Let's take the tables customers and orders as an example:

表customers

Table orders

GROUP BY example

Query how many customers live in each city. We can write SQL like this:

SELECT city, COUNT(*) AS number of customers 
FROM Customers 
GROUP BY city

result:

From the above we can see that GROUP BY aggregates customers with the same city name, and then calculates their number through the COUNT function. Before using the GROUP BY clause, you need to know some important rules.

  • The GROUP BY clause can contain any number of columns. This makes it possible to nest groups and provide more detailed control over data grouping.
  • Each column listed in the GROUP BY clause must be a retrieval column or a valid expression (but cannot be an aggregate function).
  • Except for aggregate calculation statements, each column in the SELECT statement must be given in the GROUP BY clause.
  • If there is a NULL value in the grouping column, NULL will be returned as a grouping. If there are multiple rows of NULL values ​​in the column, they will be grouped together.
  • The GROUP BY clause must appear after the WHERE clause and before the ORDER BY clause.

Comparing the above example, we can find that the usage of GROUP BY satisfies the above provisions: In addition to the aggregate function COUNT, the city is listed in the SELECT statement and the GROUP BY clause.

GROUP BY multi-table join

To query how many orders are generated in each city, we can write SQL like this.

SELECT c. city, COUNT (o. order ID) AS order quantity 
FROM Customers c 
LEFT JOIN Orders o ON c. customer ID=o. customer ID 
GROUP BY c. city

The result is:

Because there are no users in Beijing and Hangzhou to purchase the product, the order quantity is 0.

GROUP BY row weight

GROUP BY will automatically exclude duplicate data when grouping. Group cities and provinces, but do not perform any aggregation operations:

SELECT city, province 
FROM customers 
GROUP BY city, province

The result is:

This function is the same as the keyword DISTINCT function in SQL, but there will be differences in performance, so I will not expand it here.

 

Guess you like

Origin blog.csdn.net/yoggieCDA/article/details/108866776