SQL query grouping by age group

Asked

Viewed 1,546 times

1

Hello, I need a way to make an sql query that brings me the amount of male and female people. OBS: I have two tables where the first one is registered in it I have the sex column and another table that would be faixaetaria only with the nomedaxaetaria. The registration table has a column called fok_faixaetaria which is a foreign key for the faixaetaria column. I would like to perform a consultation that brings quantity of male and female people by pheasant.

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 appointment since I have 6 age group and would like to count each male and female by age group?

1 answer

3


You should list the registration table with 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
  • Thanks Solved! !

  • if you have the habit of putting (NOLOCK) in all your queries, I hope to never have to do maintenance on a system made by you... rework in the right.

  • @coreid, could mark as response?

  • @Tobymosque, I only use in tables that have a lot of competition, depends on some factors.

  • @Jeangustavoprates, in this case you can use Read Committed Snapshot Isolation, despite the problems, it’s better than reading dirty data

  • @Jeangustavoprates if I wanted to put an order by on that query how could I do it? Now I have the following situation: the registration table is related to the faixaetary table:

  • @coreid, I added a decreasing sort to the query. Isn’t this the same as the query? If you have any other questions, I believe you need to ask another question.

  • @Jeangustavoprates I’ll open another question, I’ll need your help there just a moment.

  • @JeanGustavoPrates http://answall.com/questions/83997/order-by-sql-server-em-procedure

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.