Java Reference
In-Depth Information
The
GROUP BY
clause combines records with identical values in a specified field into a single record for
this purpose, as shown in
Figure 8-1
, illustrating how to use
GROUP BY
to compute a count of
customers by state.
Figure 8-1:
Using GROUP BY to count customers by state
Because the
GROUP BY
clause combines all records with identical values in one column into a single
record, each of the column names in the
SELECT
clause must be either a column specified in the
GROUP BY
clause or a column function such as
COUNT()
or
SUM().
This means that you can't
SELECT
a list of individual customers by name and then count them as a
group by using
GROUP BY
. However, you can group on more than one column, just as you can use
more than one column with the
ORDER BY
clause. You can see an example of the use of
GROUP BY
on
more than one column in
Figure 8-2
.
Figure 8-2:
Using GROUP BY on multiple columns
Note
Every column name specified in the
SELECT
statement is also mentioned in the
GROUP
BY
clause. Not mentioning the column names in both places gives you an error. The
GROUP BY
clause returns a row for each unique combination of description and state.