Using GROUP BY and HAVING.

From SQLZOO
Revision as of 09:29, 11 July 2012 by Connor (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

BBC Country Profile

GROUP BY and HAVING <p>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
Personal tools
Namespaces

Variants
Actions
Reference
Toolbox
Google AdSense