Database Reference
In-Depth Information
Figure 10.3
GROUP BY without an aggregate.
On its own, the GROUP BY clause does not do much. Consider the results of the follow-
ing query shown in Figure 10.3:
SELECT familyname
FROM visitorbook
GROUP BY familyname
If this query stops with an error it is probably because you have not followed scripts in
Chapter 8, where we renamed the lastname column to familyname.
At first glance Figure 10.3 looks as if the GROUP BY has done little more than a SELECT
DISTINCT, in that it has picked the unique list of last names from the visitor book. If you
remember from the last time that we looked at that table there were three Normans, a
Garrett, a Davis, a Shah and someone with no last name. The query has just picked one
instance of each of them. The power of the GROUP BY clause comes when we attach it to a
query with an aggregate function. For example, take the following:
SELECT familyname, count(familyname) as familynamecount
FROM visitorbook
GROUP BY familyname
Figure 10.4 shows the results of that query. GROUP BY has done more than just select the
unique entries of the familyname column, it has grouped each similar entry into a set of
values that the aggregate functions can work with.
To demonstrate further, if we wanted to apply the GROUP BY clause to the query that
counted website hits, we can use:
SELECT id, count(*)
FROM log
GROUP BY webpageid
Search WWH ::




Custom Search