O
O
Omniverse2016-04-15 16:29:29
MySQL
Omniverse, 2016-04-15 16:29:29

How to create such a SQL query?

Hello.
There are three tables:
country
c26e0172715e4994b033f51c9869a305.png
city
3b725412032940da8e3ef3f40bfa90d6.png
countrylanguage
99a60dd525624d988a64da85309128af.png
It is necessary to display the resulting table like:
237a1aa06753469dbe7fae4869294d87.png
I managed to display everything except the number of cities and languages ​​for each region:

SELECT Continent, Region, COUNT(Name) as Countries, ROUND(AVG(LifeExpectancy), 2) as LifeDuration, SUM(Population) as Population
FROM `country`
GROUP BY Region
ORDER BY Continent, Region

How to display 2 more columns (number of cities and languages ​​for each region)?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
nozzy, 2016-04-16
@Omniverse

select
t3.Continent,
t3.Region,
sum(t3.Countries),
sum(t3.LifeDuration),
sum(t3.Population),
sum(t3.Cities),
sum(t4.Languages)
from
(
select
  t1.Code,
  t1.Continent,
  t1.Region,
  t1.Countries,
  t1.LifeDuration,
  t1.Population,
  t2.Cities
  from
   ( 
     select
     Code,
     Continent,
     Region,
     count(Name) as Countries,
     ROUND(AVG(LifeExpectancy), 2) as LifeDuration, 
     SUM(Population) as Population
     from country
     group by Code,Continent,Region
) t1 left join 
(
  select
  CountryCode,
  count(Name) as Cities
  from city
  group by CountryCode 
) t2 on t2.CountryCode = t1.Code
) t3 left join 
(
  select 
  CountryCode,
  count(Language) as Languages
  from countrylanguage
) t4 on t4.CountryCode = t3.Code

group by t3.Continent,t3.Region

I
Ihor Gevorkyan, 2016-04-15
@Igor-Maf

Good afternoon, try to look towards JOINs.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question