Difference between revisions of "Using GROUP BY and HAVING."
(Created page with "<h3>BBC Country Profile</h3> <p><code>GROUP BY</code> and <code>HAVING</code> <p>By including a <code>GROUP BY</code> clause functions such as <code>SUM</code> and <code>CO...") |
|||
| Line 1: | Line 1: | ||
<h3>BBC Country Profile</h3> | <h3>BBC Country Profile</h3> | ||
| − | <p><code>GROUP BY</code> and <code>HAVING</code> | + | <p><code>GROUP BY</code> and <code>HAVING</code></p> |
<p>By including a <code>GROUP BY</code> clause functions such as | <p>By including a <code>GROUP BY</code> clause functions such as | ||
<code>SUM</code> and <code>COUNT</code> | <code>SUM</code> and <code>COUNT</code> | ||
Revision as of 08:21, 18 July 2012
BBC Country Profile
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.
For each region show the number of countries:
bbc(name, region, area, population, gdp)
SELECT region, COUNT(name) FROM bbc GROUP BY region
SELECT region, COUNT(name) FROM bbc GROUP BY region
For each region show the total population:
bbc(name, region, area, population, gdp)
SELECT region, SUM(population) 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.
SELECT region, COUNT(name) FROM bbc WHERE population>200000000 GROUP BY region
SELECT region, COUNT(name) FROM bbc WHERE population>200000000 GROUP BY region
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
SELECT region, SUM(population) FROM bbc GROUP BY region HAVING SUM(population)>500000000