Chapter 8. Grouping and Aggregates
Data is generally stored at the lowest level of granularity needed by any of a database’s users; if Chuck in accounting needs to look at individual customer transactions, then there needs to be a table in the database that stores individual transactions. That doesn’t mean, however, that all users must deal with the data as it is stored in the database. The focus of this chapter is on how data can be grouped and aggregated to allow users to interact with it at some higher level of granularity than what is stored in the database.
Sometimes you will want to find trends in your data that will require the database server to cook the data a bit before you can generate the results you are looking for. For example, let’s say that you are in charge of sending coupons for free rentals to your best customers. You could issue a simple query to look at the raw data:
mysql> SELECT customer_id FROM rental; +-------------+ | customer_id | +-------------+ | 1 | | 1 | | 1 | | 1 | | 1 | | 1 | | 1 | ... | 599 | | 599 | | 599 | | 599 | | 599 | | 599 | +-------------+ 16044 rows in set (0.01 sec)
With 599 customers spanning more than 16,000 rental records, it isn’t feasible to determine which customers have rented the most films by looking at the raw data. Instead, you can ask the database server to group the data for you by using ...