[英]SQL: Comparing two counts from different Tables
I have 3 Tables one with every Country in the World and its token 我有3张桌子,每个国家和地区都有它的代币
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. 我试图将3个表连接在一起-但我不知道下一步该怎么做。 I'm sure I have to use nested SQL Commands. 我确定我必须使用嵌套的SQL命令。
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. 但是以某种方式,两列的count(Geo_lake.country)和count(Geo_mountain.country)似乎都具有相同的值,我不知道为什么。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.