Question

Say we I have a query that displays groups of population by country having the country as its first column, and total population of that country as its the second column.

To achieve this I have the following query:

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

Now I want to introduce two more columns to that query to display the population of males and females for each country.

What I want to achieve might look something similar to this:

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

The problem with this is that

  1. "partition by clause" is not allowed in a "group by" query
  2. "where clause" is not allowed in "partition by" clause

I hope you get the point. Please excuse my grammar and the way I titled this (couldn't know any better description).

Was it helpful?

Solution

You don't need analytic functions here:

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
;

see http://www.sqlfiddle.com/#!4/7dfa5/4

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top