Skip to main content

Putting it all together

Updated Aug 28, 2019 ·
Final challenge

This is the final challenge in the Joining Data in SQL course in Datacamp.

Tables

Below are the tables used for this challenge.

Instructions

Your task is to determine the top 10 capital cities in Europe and the Americas by city_perc, a metric you'll calculate. city_perc is a percentage that calculates the "proper" population in a city as a percentage of the total population in the wider metro area, as follows:

city_proper_pop / metroarea_pop * 100

Note:

  • Do not use table aliasing in this exercise.
  • From cities, select the city name, country code, proper population, and metro area population, as well as the field city_perc, which calculates the proper population as a percentage of metro area population for each city (using the formula provided).
  • Filter city name with a subquery that selects capital cities from countries in 'Europe' or continents with 'America' at the end of their name.
  • Exclude NULL values in metroarea_pop.
  • Order by city_perc (descending) and return only the first 10 rows.

Solution

See solution
SELECT 
name,
country_code,
city_proper_pop,
metroarea_pop,
(city_proper_pop / metroarea_pop * 100) AS city_perc
FROM cities
WHERE name IN (
SELECT capital
FROM countries
WHERE continent = 'Europe'
UNION
SELECT capital
FROM countries
WHERE continent LIKE '%America'
)
AND metroarea_pop IS NOT NULL
ORDER BY city_perc DESC
LIMIT 10;

Output (some records might not shown):

NameCountry CodeCity Proper PopMetro Area PopCity Perc (%)
LimaPER8,852,00010,750,00082.34
BogotaCOL7,878,7839,800,00080.40
MoscowRUS12,197,59616,170,00075.43
ViennaAUT1,863,8812,600,00071.69
MontevideoURY1,305,0821,947,60467.01
CaracasVEN1,943,9012,923,95966.48
RomeITA2,877,2154,353,77566.09
BrasiliaBRA2,556,1493,919,86465.21
LondonGBR8,673,71313,879,75762.49
BudapestHUN1,759,4072,927,94460.09