SQL从表中选择MAX和MIN值

时间:2015-07-13 23:11:26

标签: mysql aggregate-functions

我正在使用MySql。我有一张桌子,是根据国家表格创建的。该表拉动了该大陆并计算该表中的国家数量。

表创建工作正常。我想拉开拥有最多国家和非洲大陆数量最少的大陆。

typeof(A).GetMethod("ConsoleOutput", BindingFlags.NonPublic | BindingFlags.Instance);

我得到整张桌子:

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

抱歉,我不知道如何在这里制作一张桌子,所以这些行很麻烦。

还有什么方法可以:

  1. 将查询合并为一个并获得所需的结果?
  2. 按国家数量排列各大洲(有一个新的排名栏,例如非洲将是1,亚洲2等)?

3 个答案:

答案 0 :(得分:1)

实现此目的的一种方法是使用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
)

答案 1 :(得分: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

答案 2 :(得分:0)

查询中的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)