The statement used for grouping queries in SQL is GROUP BY, which groups the data set according to the specified column or expression and calculates the aggregate value of each group, such as sum or average. For example, GROUP BY product_name and SUM(sales_amount) calculates the total sales for each product, producing the following result: product_name, total_sales, where product_name is the grouping column and total_sales is the sum of sales for each group. GROUP BY queries can be nested to create more complex groupings, for example, nested GROUP BY product_ca
Statements for grouping queries in SQL
Grouping query is a query that groups a data set according to a specific column or expression and calculates the aggregate value (such as sum, average) of each group. In SQL, the main statement used for grouping queries is GROUP BY.
GROUP BY statement
The basic syntax of the GROUP BY statement is as follows:
<code>SELECT 列名, 聚合函数(列名) FROM table_name GROUP BY 列名</code>
Among them:
Example
Consider a table named "sales" that contains the following columns:
product_name | sales_amount | |
---|---|---|
Apple | 100 | |
Orange | 200 | |
Banana | 300 | |
Apple | 250 | |
Orange | 150 |
<code class="sql">SELECT product_name, SUM(sales_amount) FROM sales GROUP BY product_name;</code>
The query results will be As shown below:
total_sales | |
---|---|
Orange | |
Banana | |
GROUP BY queries can be nested within other queries to create more complex groupings. For example, to calculate the total sales for each product category and each product, you can use the following nested GROUP BY query:
<code class="sql">SELECT product_category, product_name, SUM(sales_amount) FROM sales GROUP BY product_category, product_name;</code>
total_sales | ||
---|---|---|
350 | Fruits | |
300 | Fruits | |
350 |
The above is the detailed content of Statements for grouping queries in sql. For more information, please follow other related articles on the PHP Chinese website!