Mastering SQL's GROUP BY
Clause for Data Aggregation
The GROUP BY
clause in SQL is a fundamental tool for summarizing and aggregating data within a table. This guide clarifies its function for database users and developers.
Imagine a table, Tab1
, containing columns a1
, a2
, a3
, etc., where values aren't necessarily unique. Executing a query like this:
<code class="language-sql">SELECT a1, a2, SUM(a3) FROM Tab1 GROUP BY a1, a2</code>
instructs the database to group rows in Tab1
based on unique pairings of a1
and a2
values. Rows sharing identical a1
and a2
values are grouped together.
For each group, the SUM(a3)
aggregate function computes the sum of a3
values across all rows within that group. The output presents these summarized groups as individual rows.
Understanding the Query's Output
The query yields one row for every unique combination of a1
and a2
found in Tab1
. This is the core function of GROUP BY
: representing each distinct data grouping with a single row.
For instance, given this Tab1
data:
a1 | a2 | a3 |
---|---|---|
1 | A | 10 |
1 | A | 20 |
2 | B | 30 |
2 | B | 40 |
The query's output would be:
a1 | a2 | SUM(a3) |
---|---|---|
1 | A | 30 |
2 | B | 70 |
This demonstrates how GROUP BY
groups rows based on a1
and a2
, independently calculating the sum of a3
for each group.
The above is the detailed content of How Does the SQL `GROUP BY` Clause Aggregate and Summarize Data?. For more information, please follow other related articles on the PHP Chinese website!