使用最小/最大子查询

问题描述 投票:0回答:1

某些国家的人口是其邻国(在同一大陆上)的三倍以上。给出国家和大洲。

enter image description here

来自https://sqlzoo.net/wiki/SELECT_within_SELECT_Tutorial,问题10

我尝试过此

SELECT w.name, w.continent 
FROM world w
WHERE w.population/3 > (SELECT min(w2.population) 
                      FROM world w2
                      WHERE w2.continent = w.continent);

此解决方案似乎有效

SELECT w.name, w.continent 
FROM world w
WHERE w.population > (SELECT 3 * MAX(w2.population) 
                      FROM world w2
                      WHERE w2.continent = w.continent AND
                            w2.name <> w.name
                     );

我正在尝试了解解决方案中的逻辑缺陷。为什么要使用max()而不使用min(),因为我们想比较人口是否是该大陆人口最少的国家的3倍?我们是否需要最小/最大场景中的w2.name <> w.name为什么?

sql postgresql subquery correlated-subquery
1个回答
0
投票

其邻居的三倍以上

意思是,同一大洲的第二高人口必须少于三分之一,并且每个大洲只有一个国家有资格。 (该大陆上的最低人口数量无关紧要。)

第二个查询带走同一大陆的所有国家/地区,但外部查询(w2.name <> w.name)中的国家除外,找到人口最多的国家并乘以3。通过条件。

此外,虽然是优雅的SQL,但是查询很昂贵,因为correlated subquery必须每行评估一次。这应该更便宜:

SELECT *
FROM  (
   SELECT DISTINCT ON (continent)
          name, continent, population
        , lead(population) OVER (PARTITION BY continent ORDER BY population DESC) AS next_population
   FROM   world
   ORDER  BY continent, population DESC
   ) sub
WHERE  population > 3 * next_population;

db <>小提琴here

© www.soinside.com 2019 - 2024. All rights reserved.