MAX查询的SQL帮助

时间:2011-07-09 19:36:08

标签: sql oracle aggregate-functions ora-00979

我有一个名为bbc的国家/地区表(名称,地区,区域,人口,gdp)

我想要一张表格,列出按地区划分的最大(人口最多)国家的地区,名称和人口。到目前为止,我已经尝试过这个:

SELECT region, name, MAX(population)
FROM bbc
GROUP BY region

它给了我一条错误消息:ORA-00979:不是GROUP BY Expression

我尝试更改为GROUP BY地区,名称,但它没有给我正确的表格

3 个答案:

答案 0 :(得分:7)

您可以对以下查询使用分析:

SELECT name, region, population
  FROM (SELECT region, name, population
             , MAX(population) OVER (PARTITION BY region) maxpop
          FROM bbc)
 WHERE population = maxpop;

内联视图为您提供了一个类似于基表的表格,以及一个包含该区域最大人口的额外列。您的顶级选择为您提供每个地区最大国家/地区的国家,地区和人口。

举例说明:

SELECT * FROM bbc;

REGION          NAME        POPULATION
--------------- -------     ----------
North America   USA         300000000
North America   Canada      100000000
North America   Mexico       50000000
South America   Brazil       50000000
South America   Argentina    40000000
South America   Venezuela    20000000

添加分析函数:

SELECT region, NAME, population
     , MAX(population) OVER (PARTITION BY region) maxpop
  FROM bbc;

REGION          NAME                POPULATION      MAXPOP
--------------- -------             ----------      ----------
North America   USA                 300000000       300000000
North America   Canada              100000000       300000000
North America   Mexico               50000000       300000000
South America   Brazil               50000000        50000000
South America   Argentina            40000000        50000000
South America   Venezuela            20000000        50000000

然后是成品:

NAME    REGION             POPULATION
------- ---------------    -----------
USA     North America       300000000
Brazil  South America        50000000

再一次编辑。您可以避免使用嵌套选择,但不能避免子查询:

SELECT NAME, region, population
  FROM bbc
 WHERE (region, population) IN
       (SELECT region, MAX(population)
          FROM bbc
         group by region);

答案 1 :(得分:3)

这是最简单,最简单的方法,因为Oracle有元组测试,它可以缩短代码:

首先,获取每个地区的最大人口数量:

SELECT region, MAX(population)
FROM bbc
GROUP BY region

然后测试各国反对它:

select region, name, population 
from bbc 
where (region, population) in
      (SELECT region, MAX(population)
       FROM bbc
       GROUP BY region)
order by region

如果要支持许多RDBMS,请使用EXISTS:

select region, name, population 
from bbc o
where exists
      (SELECT null -- neutral. doesn't invoke Cargo Cult Programming ;-)
       FROM bbc
       WHERE region = o.region 
       GROUP BY region
       HAVING o.population = MAX(population) )
order by region

此处测试的查询,两者都有类似的输出:http://sqlzoo.net/0.htm

http://www.ienablemuch.com/2010/05/why-is-exists-select-1-cargo-cult.html

答案 2 :(得分:0)

在绝大多数花瓶中,导致ORA-00979错误是因为GROUP BY子句中未包含非聚合列。在这种情况下,您还需要在GROUP BY子句中包含 name 。此外,您不应该在FROM语句中调用MAX函数。

SELECT region, name, MAX(population)
FROM bbc
GROUP BY region, name