简体   繁体   English

sql子查询

[英]sql sub-queries

Can anyone help me with the following:任何人都可以帮助我解决以下问题:

Some countries have populations more than three times that of any of their neighbours (in the same region).一些国家的人口是其邻国(同一地区)的三倍以上。 Give the countries and regions.给出国家和地区。

my try:我的尝试:

select x.name, x.region
from bbc x
where x.population >all
(select population*3
from bbc y
where y.region = x.region)

syntax is correct but no records are returned (should return 3 rows)语法正确但没有返回记录(应返回 3 行)

Find each country that belongs to a region where all populations are less than 25000000. Show name, region and population.找出所有人口少于 2500 万的地区的每个国家。显示名称、地区和人口。

my try:我的尝试:

select name, region, population
from bbc
where region not in 
(select distinct region from bbc 
where population >= 25000000)

I used "not in".我用了“不在”。 Is there a way to use "in" ?有没有办法使用“in”?

SELECT name, region 
FROM bbc x 
WHERE population/3 >= ALL
    (SELECT population
     FROM bbc y
     WHERE y.region=x.region
     AND x.name != y.name)

Elad, your first answer is almost correct, just missing one very key component: Elad,你的第一个答案几乎是正确的,只是缺少一个非常关键的组成部分:

SELECT x.name, x.continent
  FROM world x
  WHERE x.population >ALL(SELECT population*3
                            FROM world y
                            WHERE y.continent = x.continent
                            AND x.name<>y.name)

You see when you do the sub-query that checks x.population>3*(all of y.populations for same continent) YOU MUST SPECIFY NOT TO CHECK AGAINST THE SAME COUNTRY ;您会看到,当您执行检查 x.population>3*(all of y.populations for same Continent) 的子查询时,您必须指定不检查同一国家 otherwise you are stating to check that x>3x which is mathematically impossible.否则你要检查 x>3x 这在数学上是不可能的。

A couple of other solutions, added for interest.一些其他解决方案,增加了兴趣。

First query:第一个查询:

SELECT name, 
       region 
FROM   bbc x 
WHERE  population > 
       -- this sub query finds each neighbour (not including itself) and returns the max populations multiplied by 3
       (SELECT 3 * MAX(population) 
        FROM   bbc y 
        WHERE  x.region = y.region 
               AND x.name <> y.name) 

Second query:第二个查询:

SELECT name, 
       region, 
       population 
FROM   bbc x 
WHERE  population < ALL 
       -- the ALL keyword allows comparison to be made against all the values in a list 
       -- this sub query finds each country that belongs to a region with populations less than 25 million and returns this as a list
       (SELECT population 
        FROM   bbc y 
        WHERE  y.region = x.region 
               AND population > 25000000) 

For the first :为了第一 :

You have to divide the work.你必须分工。 Step one, find the neighbours for a country.第一步,找到一个国家的邻居。 This have to be an auto join :这必须是自动加入:

SELECT *
FROM bbc country
    INNER JOIN bbc neighbours
        ON country.region = neighbours.region
        AND country.name != neighbours.name

Don't forget to exclude self country from the neighbours !不要忘记将自己的国家排除在邻居之外!

Second, you can count how much neighbours for a country have the right population :其次,您可以计算一个国家有多少邻国拥有合适的人口:

sum(CASE WHEN country.population > neighbours.population * 3 THEN 1 ELSE 0 END)
(Group by country !)

Compare with the total and you are done !与总数比较,你就完成了!

SELECT countryName 
FROM
(
    SELECT sum(CASE WHEN country.population > neighbours.population * 3 THEN 1 ELSE 0 END) as okNeighbours,
           count(*) as totalNeighbours
           country.name as countryName
    FROM bbc country
        INNER JOIN bbc neighbours
            ON country.region = neighbours.region
            AND country.name != neighbours.name
    GROUP BY country.name
)
WHERE totalNeighbours = okNeighbours

For the second :对于第二个:

SELECT name, region, population
FROM bbc
WHERE region IN (
    SELECT region
    FROM bbc
    GROUP BY region
    HAVING SUM(CASE WHEN population >= 25000000 THEN 1 ELSE 0 END) = 0
)
SELECT name, region
FROM   bbc x
WHERE  population > 3 *
       (SELECT population 
        FROM bbc y 
        WHERE x.region=y.region
        ORDER BY population DESC limit 1,1)

population you are looking after is 3x the value of second highest population, thats limit 1,1.您正在关注的人口是第二高人口价值的 3 倍,即限制 1,1。 Second question is missing a 0, then its correct.第二个问题缺少一个 0,那么它是正确的。

SELECT name, region, population 
FROM   bbc x
WHERE  (SELECT SUM(population) 
        FROM bbc y
        WHERE x.region=y.region) < 250000000
select name, region from bbc x
where population > all
(select 3*population from bbc y 
where y.region=x.region and population > 0 and x.name <> y.name)

To find the name of all countries in a continent, where all countries have a population less than 25000000, do the following:要查找一个大陆上所有国家的名称,其中所有国家的人口都少于 2500 万,请执行以下操作:

  1. Find the max(population) grouped by continent找到按大陆分组的 max(population)

     (SELECT max(population) FROM world GROUP BY continent)

Note: since the maximum is less than your number, you know all are注意:由于最大值小于您的数字,您知道所有都是

  1. Find the continent寻找大陆

    SELECT continent FROM world WHERE population IN(SELECT max(population) FROM world GROUP BY continent) AND population <= 25000000)
  2. Put it all together to get the name, continent, population把它们放在一起得到名字,大陆,人口

    SELECT name, continent, population FROM world WHERE continent IN(SELECT continent FROM world WHERE population IN(SELECT max(population) FROM world GROUP BY continent) AND population <= 25000000)
SELECT name,continent FROM world x WHERE population > ALL(SELECT population*3
FROM world y WHERE x.continent=y.continent and x.name!=y.name)

I've just encountered this problem right now, so sorry if I'm years late.我现在刚刚遇到这个问题,如果我晚了几年,很抱歉。 haha!哈哈! This is how I did it.我就是这样做的。 The purpose of the main select statement is to compare every country then we twist it a little bit in the inner select statement which compares country in the same continent/region only.主要 select 语句的目的是比较每个国家/地区,然后我们在内部 select 语句中稍微扭曲它,该语句仅比较同一大陆/地区的国家/地区。 Also we added a condition where the country from outer select shouldn't be compared with itself.我们还添加了一个条件,即不应将外部选择的国家/地区与自身进行比较。

select x.name, x.continent
from world x
where x.population > 3 * (select y.population from world as y where x.continent = y.continent and x.name <> y.name order by y.population desc limit 1)

For the second query, "Find each country that belongs to a region where all populations are less than 25000000. Show name, region and population."对于第二个查询,“查找属于所有人口少于 2500 万的地区的每个国家/地区。显示名称、地区和人口。” (ref. sqlzoo.net, 'SELECT within SELECT', question 3b ) (参考sqlzoo.net,'SELECT 中的 SELECT',问题 3b

SELECT name, region, population FROM bbc
 WHERE region NOT IN
     ( SELECT DISTINCT region FROM bbc
        WHERE population >= 25000000 )
   AND region IN
     ( SELECT DISTINCT region FROM bbc
        WHERE population < 25000000 )

Find each country that belongs to a continent where all populations are less than 25000000. Show name, continent and population找出所有人口少于 2500 万的大陆所属的每个国家。显示名称、大陆和人口

So first need to find continent where any country should not have population > 25000000.所以首先需要找到任何国家不应该有人口> 25000000的大陆。

SELECT name, continent, population from world x
WHERE continent in

 (SELECT continent FROM world y

    WHERE 25000000 > 
      (select max(population) from world z
           where y.continent = z.continent))

Can anyone help me with the following:任何人都可以在以下方面为我提供帮助:

Some countries have populations more than three times that of any of their neighbours (in the same region).一些国家的人口是其邻国(在同一地区)的三倍以上。 Give the countries and regions.给出国家和地区。

my try:我的尝试:

select x.name, x.region
from bbc x
where x.population >all
(select population*3
from bbc y
where y.region = x.region)

syntax is correct but no records are returned (should return 3 rows)语法正确,但不返回任何记录(应返回3行)

Find each country that belongs to a region where all populations are less than 25000000. Show name, region and population.查找属于所有人口均少于2500万的区域的每个国家/地区。显示名称,区域和人口。

my try:我的尝试:

select name, region, population
from bbc
where region not in 
(select distinct region from bbc 
where population >= 25000000)

I used "not in".我用“不在”。 Is there a way to use "in" ?有没有一种使用“ in”的方法?

This will also work这也将起作用

       SELECT name, continent 
       FROM world x 
       WHERE population >= 3* (SELECT population FROM world y
       WHERE y.continent=x.continent
       AND population>0 ORDER BY population DESC LIMIT 1 OFFSET 1 )

In the inner query I am selecting the second highest population in the respective continent and in the where I am checking whether second highest one is 3 times smaller or not in population.在内部查询中,我选择了各自大陆中第二高的人口,并在其中检查第二高的人口是否比人口小 3 倍。

For the first question, the SQL script is :对于第一个问题,SQL 脚本是:

SELECT w1.name,w1.continent
FROM world w1
WHERE w1.population > 3 * (
SELECT max(w2.population)
FROM world w2
WHERE w2.continent = w1.continent
AND w2.name <> w1.name
GROUP BY w2.continent
)

I've been going through these little challenges on SQLZOO as well, and these two particular questions I found tricky.我也在 SQLZOO 上经历了这些小挑战,我发现这两个问题很棘手。

Some countries have populations more than three times that of any of their neighbours (in the same continent).一些国家的人口是其邻国(同一大陆)的三倍以上。 Give the countries and continents.给国家和大陆。

My first attempt was:我的第一次尝试是:

SELECT name, continent
      FROM world x
WHERE population > ALL (SELECT population*3
                              FROM world y
                       WHERE x.continent = y.continent)

Which seemed logical to me.这对我来说似乎是合乎逻辑的。 Until I realised that if I was checking every population against every other population within the continent, including itself , then I'd never get any results back, as the population of a country will never be more than itself times three.直到我意识到,如果我将大陆上的每个人口(包括它自己)与所有其他人口进行核对,那么我永远不会得到任何结果,因为一个国家的人口永远不会超过其自身的三倍。 So you need to check every other country, excluding the country you're checking against.因此,您需要检查所有其他国家/地区,不包括您要检查的国家/地区。

There are also two countries in the table that have a population of NULL, so you also have to exclude these to satisfy the question.表中还有两个国家的人口为 NULL,因此您还必须排除这些国家才能满足问题。

SELECT name, continent
      FROM world x
WHERE population > ALL (SELECT population*3
                              FROM world y
                       WHERE x.continent = y.continent
                       AND x.name <> y.name)
AND population > 0

Use this query:使用此查询:

SELECT name, continent 
FROM world x WHERE population/3 > ALL (SELECT population  
                                       FROM world y 
                                       WHERE x.continent = y.continent 
                                             AND x.name != y.name 
                                             AND population > 0)

For the first question : you have to add another line of code AND B.name <> A.name对于第一个问题:您必须添加另一行代码AND B.name <> A.name

SELECT name, region  
FROM bbc A
WHERE A.population/3 >= ALL(SELECT population FROM bbc B 
                                              WHERE B.region = A.region 
                                              AND   B.name  <> A.name)

For the Second question : you can get rid of both NOT IN and IN by using ALL对于第二个问题:您可以使用ALL摆脱NOT ININ

SELECT name, region, population
FROM bbc A
WHERE 25000000 >= ALL(SELECT population FROM bbc B 
                                        WHERE B.region = A.region)

此查询将帮助您。

select name,continent from world a where population >all(select population*3 from world b where a.continent=b.continent and a.name!=b.name)

The correct answer shows only 3 country results in the entire world.正确答案仅显示全世界 3 个国家/地区的结果。 Maybe I'm missing something.也许我错过了一些东西。 There should be many countries that has 3x+ population to their neighbor, assuming neighbor is defined only as a country in the same continent.假设邻居仅被定义为同一大陆的一个国家,那么应该有许多国家的人口是其邻居的 3 倍以上。

IE, Afghanistan has 25million population, while Bahrain in Asia has 1.2 mil, which makes Afghanistan way bigger than 3x population compared to its Bahrain neighbor. IE,阿富汗有 2500 万人口,而亚洲的巴林有 120 万人口,这使得阿富汗的人口是其邻国巴林的 3 倍多。 So that should be a correct answer selection too right?所以这也应该是一个正确的答案选择吧?

此查询将返回所需的输出

SELECT countryName, continent FROM ( SELECT sum(CASE WHEN w1.population > w2.population * 3 THEN 1 ELSE 0 END) as finaloutput, count(*) as totalNeighbours, w1.name as countryName, w1.continent as continent FROM world w1 INNER JOIN world w2 ON w1.continent= w2.continent AND w1.name != w2.name GROUP BY country.name ) as tbl WHERE totalNeighbours = finaloutput

On your second query you can do this without IN or NOT IN :在您的第二个查询中,您可以在没有INNOT IN情况下执行此操作:

SELECT name, region, population
from bbc
where population >= 25000000

If you insist on using IN however just reverse the condition:如果您坚持使用 IN 但是只需颠倒条件:

select name, region, population
from bbc  where region not in
(select distinct region from bbc   where population < 25000000)

If I understand your data correctly, you have only one table.如果我正确理解您的数据,那么您只有一张表。 So when you所以当你

Select distinct region from bbc where population >=25000000)

you are really getting a list of all the countries that have 25mil and listing their region names.你真的得到了所有拥有 2500 万人口的国家的列表,并列出了他们的地区名称。 To get a list of regions, you have to SUM the populations要获得区域列表,您必须对人口求和

Select region, sum(population) as regionpop from bbc group by region having sum(population)>25000000

Now you can select the countries from those regions and show their information现在您可以从这些地区中选择国家并显示其信息

Select name, region, population from bbc where region in 
(Select region from bbc group by region having sum(population)>25000000)

For the first query, would something like this work?对于第一个查询,这样的事情会起作用吗?

SELECT
a.region  , b.*
FROM 
bbc  a
INNER JOIN 
(SELECT population , (population  * 3) AS PopX3, region  FROM bbc  ) b
ON
a.population  < PopX3
AND
a.region <> b.region

For your "3 times population" query, no sub query is required... just a self-join on region, and the first instance population is > second instance population * 3. In the case of a self-join getting to its own country in the same region, it would never be returned since its population would never be greater than 3 times its own value.对于您的“3 次人口”查询,不需要子查询...只是区域上的自联接,并且第一个实例人口是 > 第二个实例人口 * 3。在自联接的情况下同一地区的国家,它永远不会被归还,因为它的人口永远不会超过其自身价值的 3 倍。

Still waiting on feedback of other population question posted as comment in your original question...仍在等待其他人口问题的反馈在您的原始问题中作为评论发布...

select
      b1.Name,
      b1.Region,
      b1.Population,
      b2.Name SmallerCountry,
      b2.Population SmallerPopulation
   from
      bbc b1
         join bbc b2
             on b1.Region = b2.Region
            AND b1.Population > b2.Population * 3
Select name , continent 
from world x 
where population >  All(
  Select population* 3 from world y 
  where x.continent = y.continent and x.name != y.name);

Find the continents where all countries have a population <= 25000000. Then find the names of the countries associated with these continents.找出所有国家人口<= 25000000 的大陆。然后找出与这些大陆相关联的国家的名称。 Show name, continent and population.显示姓名、大陆和人口。

solution解决方案

select name, continent, population
from world x where 25000000>= 
all(select population from world z where x.continent = z.continent);

Find the continents where all countries have a population <= 25000000 .找出所有国家population <= 25000000的大陆。 Then find the names of the countries associated with these continents.然后找到与这些大陆相关联的国家的名称。 Show name , continent and population .显示namecontinentpopulation

This is my solution and it seems to be the simplest one from all the above:这是我的解决方案,它似乎是上述所有解决方案中最简单的一个:

SELECT name, continent, population FROM world 
WHERE continent NOT IN (SELECT continent FROM world WHERE population > 25000000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM