Home >Database >Mysql Tutorial >How Does GROUP BY with Multiple Columns Work in SQL?
Understanding SQL's GROUP BY with Multiple Columns
The SQL GROUP BY
clause is a powerful tool for data aggregation. While using GROUP BY
with a single column is straightforward, employing it with multiple columns requires a deeper understanding.
When you use GROUP BY x, y
, the combination of x
and y
values defines the grouping criteria. Data is grouped into unique combinations of x
and y
values, unlike GROUP BY x
which groups solely based on x
.
Let's illustrate with the "Subject_Selection" table:
Subject | Semester | Attendee |
---|---|---|
ITB001 | 1 | John |
ITB001 | 1 | Bob |
ITB001 | 1 | Mickey |
ITB001 | 2 | Jenny |
ITB001 | 2 | James |
MKB114 | 1 | John |
MKB114 | 1 | Erica |
A GROUP BY Subject
query yields:
Subject | Count |
---|---|
ITB001 | 5 |
MKB114 | 2 |
Showing 5 entries for ITB001 and 2 for MKB114.
However, a GROUP BY Subject, Semester
query produces:
Subject | Semester | Count |
---|---|---|
ITB001 | 1 | 3 |
ITB001 | 2 | 2 |
MKB114 | 1 | 2 |
Here, grouping is based on both Subject
and Semester
. We see 3 attendees for ITB001 in semester 1, 2 in semester 2, and 2 for MKB114 in semester 1.
In essence, GROUP BY
with multiple columns allows simultaneous grouping by multiple criteria, revealing data distribution and relationships between different attributes.
The above is the detailed content of How Does GROUP BY with Multiple Columns Work in SQL?. For more information, please follow other related articles on the PHP Chinese website!