SUM and COUNT

From SQLZOO

Revision as of 15:35, 9 July 2012 by Connor(Talk | contribs)(Created page with "==BBC Country Profile: Aggregate functions== This tutorial is about aggregate functions such as COUNT, SUM and AVG. An aggregate function takes many values and delivers just o...")

BBC Country Profile: Aggregate functions

This tutorial is about aggregate functions such as COUNT, SUM and AVG. An aggregate function takes many values and delivers just one value. For example the function SUM would aggregate the values 2, 4 and 5 to deliver the single value 11.

Exercises

Using SUM, Count, MAX, DISTINCT and ORDER BY.

Show the total population of the world.

bbc(name, region, area, population, gdp)

SELECTSUM(population)FROM bbc

SELECTSUM(population)FROM bbc

List all the regions - just once each.

SELECTDISTINCT(region)FROM bbc

Give the total GDP of Africa

SELECTSUM(gdp)FROM bbc
WHERE region ='Africa'

How many countries have an area of at least 1000000

SELECTCOUNT(region)FROM bbc
WHERE area >=1000000

What is the total population of ('France','Germany','Spain')

SELECTSUM(population)FROM bbc
WHERE name IN('France','Germany','Spain')

Using GROUP BY and HAVING

For each region show the region and number of countries.

SELECT region,COUNT(name)FROM bbc
GROUPBY(region)

For each region show the region and number of countries with populations of at least 10 million.

SELECT region,COUNT(name)FROM bbc
WHERE population >=10000000GROUPBY(region)