SQL query grouping by age group

1

Hello, I need a way to do an sql query that will bring me the amount of male and female people. NOTE: I have two tables where the first one is registered in it I have the sex column and another table that would be entered only with the addressname. The register table has a column named fok_faixaetaria which is a foreign key for the column array. I would like to conduct a consultation that would bring a lot of people, male and female, by area.

SELECT COUNT(case when sexo= 'Masculino' then 1 end) AS Masculino,
COUNT(case when sexo= 'Feminino' then 1 end) AS Feminino FROM cadastro
where dataInicial = '01/08/2015' and dataFinal = '31/08/2015' 

How can I make the query being that I have 6 age range and would like to count each male and female by age group?

    
asked by anonymous 02.09.2015 / 15:56

1 answer

3

You should relate the registration table to the age range table and group the results through the age range column.

Use the example below:

SELECT 
      COUNT(case when sexo= 'Masculino' then 1 end) AS Masculino,
      COUNT(case when sexo= 'Feminino' then 1 end) AS Feminino, 
      FE.FAIXAETARIA AS [Faixa Etaria]
FROM 
      cadastro c (nolock)
      LEFT JOIN FAIXAETARIA FE (NOLOCK) ON FE.FAIXAETARIA = C.FOK_FAIXAETARIA
WHERE 
      dataInicial = '01/08/2015' and dataFinal = '31/08/2015' 
GROUP BY
      FE.FAIXAETARIA
ORDER BY
      FE.FAIXAETARIA DESC
    
02.09.2015 / 16:05