In this chapter, you??™ll learn how to use the database to perform two common tasks:
grouping and aggregation. Let??™s look at how these tasks are useful, and then work through
an example that uses them for reporting.
Grouping and Aggregation
Grouping refers to a way to reduce a table into a subset, where each row in the subset
represents the set of records having a particular grouped value or values. For example, if
you were tracking automobile accidents, and you had a table of persons, with their age
and number of accidents, you could group by age and retrieve every distinct age in the
database. In other words, you would get a list of the age of every person, with the duplicates
removed.
19
C H A P T E R 2
If you were using an Active Record model named Person with an age column, you
could find all of the distinct ages of the people involved, as follows:
ages = Person.find(:all, :group=>'age')
However, to perform useful work on grouped queries, you??™ll typically use aggregate
functions. For example, you??™ll need to use aggregate functions to retrieve the average
accidents per age group or the count of the people in each age group.
Pages:
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55