The GROUP BY statement is used to group a data set by a specified column and aggregate data from the same group. Syntax: SELECT column name 1, column name 2, ...FROM table name GROUP BY grouping column name; it can be used in conjunction with aggregate functions, such as SUM, COUNT, AVG, to summarize data within a group. Benefits include simplifying data analysis, identifying pattern trends, and improving query performance.
Usage of GROUP BY statement in SQL
What is GROUP BY statement?
The GROUP BY statement is used to group rows in a data set and aggregate data in the same group into a single result row.
Syntax
<code class="sql">SELECT 列名1, 列名2, ... FROM 表名 GROUP BY 分组列名;</code>
Group columnSpecify the column by which to group the data. You can group by one or more columns.
Aggregation functions can be used to aggregate data in a group, such as SUM, COUNT, AVG.
Usage
The GROUP BY statement is often used with aggregate functions to calculate summary values for data in a group. For example:
<code class="sql">-- 计算销售表中每个产品的总销量 SELECT ProductName, SUM(Quantity) AS TotalQuantity FROM Sales GROUP BY ProductName;</code>
Result
The GROUP BY statement returns a result set that contains the unique values for the specified column in the grouping column and the calculated results of the aggregate column.
Benefits
Example
Suppose you have a table containing the following person data:
Name | Age | Gender |
---|---|---|
John | 25 | Male |
Mary | 30 | Female |
Bob | 40 | Male |
Alice | 28 | Female |
Tom | 35 | Male |
The following GROUP BY query will group people by gender and calculate each group Number of people:
<code class="sql">SELECT Gender, COUNT(*) AS Count FROM People GROUP BY Gender;</code>
Result:
Count | |
---|---|
3 | |
2 |
The above is the detailed content of How to use group by in sql. For more information, please follow other related articles on the PHP Chinese website!