问题
I have 3 Tables one with every Country in the World and its token
NAME CODE
Afghanistan AFG
Albania AL
Algeria DZ
American Samoa AMSA
Andorra AND
Angola ANG
Anguilla AXA
(...)
And and a Table of all lakes and another one of all mountains in these countries.
LAKE CODE
Bodensee A
Neusiedlersee A
Lake Prespa AL
Lake Ohrid AL
Lake Skutari AL
Lake Eyre AUS
Lake Jindabyne AUS
Lake Hume AUS
Lake Eucumbene AUS
Lake Hume AUS
Lake Burley Griffin AUS
(...)
MOUNTAIN CODE
Hochgolling A
Hochgolling A
Zugspitze A
Grossglockner A
Jezerce AL
Korab AL
Uluru AUS
Mt. Kosciuszko AUS
Mt. Bogong AUS
Musala BG
Illampu BOL
Sajama BOL
Licancabur BOL
(...)
I now have to show the countries which have a smaller amount of mountains than lakes. And I tried now for hours but can´t find an approach to this problem. I tried to Join the 3 tables together - but I can't figure out what to do next. I'm sure I have to use nested SQL Commands.
Here is my attempt on counting the lakes and mountains of each country
SELECT Country.name, count(Geo_lake.code), count(Geo_mountain.code)
From Country
INNER JOIN Geo_lake On (Country.code = geo_lake.code)
INNER JOIn Geo_mountain On (Country.code = geo_mountain.code)
Group by Country.name;
But somehow both columns count(Geo_lake.country) and count(Geo_mountain.country) appear to have the same values I don´t know exactly why.
回答1:
Start off by getting the sums for each individually:
# Sum of lakes
SELECT code, count(*) AS sum FROM lakes GROUP BY code
# Sum of mountains
SELECT code, count(*) AS sum FROM mountains GROUP BY code
Then join the results together and select all rows where the sum of the mountains for a country are less than the number of lakes:
SELECT l.code AS code, l.sum AS lake_count, m.sum AS mountain_count
FROM
(SELECT code, count(*) AS sum FROM lakes GROUP BY code) AS l JOIN
(SELECT code, count(*) AS sum FROM mountains GROUP BY code) AS m
ON l.code = m.code
WHERE m.sum < l.sum
来源:https://stackoverflow.com/questions/35215541/sql-comparing-two-counts-from-different-tables