有没有办法对具有“group by”子句的查询进行分区?

时间:2012-07-19 07:12:43

标签: plsql oracle10g analytic-functions

假设我们有一个查询显示按国家/地区划分的人口组,其中该国家/地区为第一列,该国家/地区的总人口为第二列。

为实现这一目标,我有以下问题:

select 
  i.country,
  count(1) population
from
  individual i
group by
  i.country

现在我想在该查询中再引入两列,以显示每个国家/地区的男性和女性人口。

我想要达到的目标可能与此相似:

select 
  i.country,
  count(1) population total_population,
  count(1) over (partition by 1 where i.gender='male') male_population,
  count(1) over (partition by 1 where i.gender='female') female_population,
from
  individual i
group by
  i.country

问题在于

  1. “分区依据”不允许在“分组依据”查询
  2. 中使用
  3. “where by”在“分区依据”条款中不允许
  4. 我希望你明白这一点。请原谅我的语法和我的标题(不知道更好的描述)。

1 个答案:

答案 0 :(得分:3)

您不需要分析功能:

select 
  i.country
 ,count(1) population
 ,count(case when gender = 'male' then 1 end) male
 ,count(case when gender = 'female' then 1 end) female
from
  individual i
group by
  i.country
;

请参阅http://www.sqlfiddle.com/#!4/7dfa5/4

相关问题