GROUP BY
and HAVING
By including a GROUP BY
clause functions such as SUM
and COUNT
are applied to groups of items sharing values. When you specify GROUP BY region
the result is that you get only one row for each different value of region
. All the other columns must be "aggregated" by one of SUM
, COUNT
...
The HAVING
clause allows use to filter the groups which are displayed. The WHERE
clause filters rows before the aggregation, the HAVING
clause filters after the aggregation.
If a ORDER BY
clause is included we can refer to columns by their position.
SELECT region, COUNT(name)
FROM bbc
GROUP BY region
SELECT region, SUM(population)
FROM bbc
GROUP BY region
WHERE and GROUP BY
The WHERE filter takes place before the aggregating function. For each relevant region show the number of countries that has a population of at least 200000000. (You may recall that there are 4 such countries: China, India, USA and Indonesia)
SELECT region, COUNT(name)
FROM bbc
WHERE population>200000000
GROUP BY region
REGION | COUNT(NAME) |
---|---|
Asia-Pacific | 2 |
South Asia | 1 |
Americas | 1 |
GROUP BY and HAVING
The HAVING clause is tested after the GROUP BY. You can test the aggregated values with a HAVING clause.
Show the total population of those regions with a total population of at least half a billion.
SELECT region, SUM(population)
FROM bbc
GROUP BY region
HAVING SUM(population)>500000000
REGION | SUM(POPULATION) |
---|---|
South Asia | 1488138000 |
Asia-Pacific | 2173791900 |
Europe | 818020000 |
Africa | 698081725 |
Americas | 879639000 |