0

在此处输入图像描述

我正在尝试学习一些 SQL,所以我一直在搞乱示例世界模式。对于此查询,目标是针对每个大陆检索预期寿命大于该大陆平均水平的国家/地区的首都。

下面的代码是我的尝试,但我在 where 语句中收到1111 错误。任何帮助将非常感激!

SELECT continent AS Continent,
       city.name AS Capital
FROM city,
     country c1
WHERE c1.capital = city.id
  AND avg(LifeExpectancy) <
    (SELECT avg(LifeExpectancy)
     FROM country c2
     WHERE c2.continent = c1.continent );
4

2 回答 2

1

您必须正确连接表countrycity返回lifeexpectancy每个大陆平均值的查询:

select co.code, ci.name
from country co
inner join city ci on ci.id = co.capital
inner join (
  select continent, avg(lifeexpectancy) avg_lifeexpectancy
  from country
  group by continent
) t on t.continent = co.continent and t.avg_lifeexpectancy < co.lifeexpectancy
于 2020-09-08T16:16:33.727 回答
1

根据您的问题陈述,您不需要首都的平均预期寿命,只需要与首都对应的国家/地区的预期寿命大于该大陆的平均水平。因此,我在下面的查询中进行了这些调整。

让我知道这行得通。

SELECT continent AS Continent,
       city.name AS Capital
FROM city,
     country c1
WHERE c1.capital = city.id
  AND c1.LifeExpectancy >
    (SELECT avg(LifeExpectancy)
     FROM country c2
     WHERE c2.continent = c1.continent );
于 2020-09-08T16:01:18.697 回答