繁体   English   中英

SQL从表中选择MAX和MIN值

[英]SQL Select MAX and MIN value from a table

我正在使用MySql。 我有一个从国家表格创建的表格。 表格将拉动大陆,并计算该表格中的国家/地区数量。

表创建工作正常。 然后,我想拉动国家数量最多的大陆和国家数量最少的大陆。

create table cops as (select 
continent,
count(name) as number_of_countries
from country
group by continent);

select 
continent,
number_of_countries
from cops
where number_of_countries = (select MIN(number_of_countries)) OR (select MAX(number_of_countries));

我得到整个桌子:

continent   number_of_countries
Antarctica  5
South America   14
Oceania 28
North America   37
Europe  46
Asia    51
Africa  58

我只想要:

continent   number_of_countries
Antarctica  5
Africa  58

抱歉,我不知道如何在此处制作桌子,所以行很麻烦。

另外,有什么方法可以:

  1. 将查询合并为一个并获得所需的结果?
  2. 通过国家/地区对大陆进行排名(具有新的排名列,例如,非洲将为1,亚洲为2,等等)?

一种实现此目的的方法是使用UNION ,它可以让您合并来自多个查询的结果(前提是它们具有相同的列)。 例如,

-- Get continent with greatest number of countries.
SELECT
    continent,
    number_of_countries
FROM cops
WHERE continent = (
    SELECT continent
    FROM cops
    ORDER BY number_of_countries DESC
    LIMIT 1
)

UNION

-- Get continent with least number of countries.
SELECT
    continent,
    number_of_countries
FROM cops
WHERE continent = (
    SELECT continent
    FROM cops
    ORDER BY number_of_countries ASC
    LIMIT 1
)

由于您已经有了一个名为cops的表格,该表格可以保存每个大洲的国家数量,因此您可以执行以下操作:

-- The UNION approach
select *
from cops
where number_of_countries = (select min(number_of_countries) from cops)
union
select *
from cops
where number_of_countries = (select max(number_of_countries) from cops);

或类似这样的东西:

select *
from cops
where number_of_countries in (
          (select min(number_of_countries) from cops),
          (select max(number_of_countries) from cops)
      );

关于第二个问题:使用用户变量:

select cops.*, @n := n + 1 as rank
from (select @n := 0) as init,
     cops
order by number_of_countries desc

您的查询中的WHERE子句是错误的。 用类似这样的东西代替应该给您想要的结果:

  where number_of_countries = ( SELECT MIN(number_of_countries) FROM cops )
     or number_of_countries = ( SELECT MAX(number_of_countries) FROM cops )

还有其他查询模式将给出相同的结果。 作为一种模式的示例,使用对内联视图的联接:

  SELECT c.continent
       , c.number_of_countries
    FROM ( SELECT MIN(n.number_of_countries) AS min_noc
                , MAX(n.number_of_countries) AS max_noc
             FROM cops n
         ) m
    JOIN cops c
      ON c.number_of_countries IN (m.min_noc,m.max_noc)

暂无
暂无

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

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