Aggregations

Beginner

As we saw in the Math section, SQL provides many ways to calculate aggregate measures and statistics. We can use a mathematical function like SUM() to sum a list of a values, or AVG() to calculate the average of a list of values.

Sometimes, however, it’s useful to run that aggregation/calculation multiple times, for each separate group in our data.

For example, take a look at the following table calls, which contains call records for a telemarketing company:


We could use a a mathematical function like COUNT to count the number of calls in the table, giving us an overall/total number of calls:

SELECT COUNT(*) 
FROM calls

# Result
# 

But what if we want to do something a bit more nuanced, like counting the number of calls on each separate day, or counting the number of calls made by each separate agent? Rather than generating a single number/count using COUNT, we’d need to produce tables like this:

Luckily, SQL provides a handy operator - GROUP BY - which lets us do exactly that. In this chapter, we’ll find out how.