Prev | Current Page 44 | Next

David Berube

"Practical Reporting with Ruby and Rails"


You??™ve probably encountered a number of aggregate functions already. Some common
ones are MAX and MIN, which give you the maximum and minimum value; AVG, which
gives you the average value; SUM, which returns the sum of the values; and COUNT, which
returns the total number of values. Each database engine may define different statistical
functions, but nearly all provide those just mentioned.
Continuing with the Active Record model named Person with an age column, you
could find the highest age from your table as follows:
oldest_age = Person.calculate(:max, :age)
Note that calculate takes the max function??™s name, as a symbol, as its first argument,
but Active Record also has a number of convenience functions named after their respective
purposes: count, sum, minimum, maximum, and average. For example, the following two
lines are identical:
average_accident_count = Person.calculate(:avg, :accident_count)
average_accident_count = Person.average(:accident_count)
Both print out the average number of accidents for all rows.


Pages:
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56