Problems in Mysql query

Asked

Viewed 94 times

2

I’m having difficulty in performing a query between 4 tables, being them. States > Municipalities > Deaths > Population The query is returning the value of the population with a larger number than the real one... Can anyone help me regarding this query?

select estados.nome, sum(obitos.quantidade) as Obitos,
        sum(populacao.quantidade) as Pupolação

    from estados
    inner join municipios on (estados.idEstado = municipios.idEstado)
    inner join obitos on (municipios.idMunicipio = obitos.idMunicipio)
    inner join populacao on (municipios.idMunicipio = populacao.idMunicipio)
    where obitos.data between '2008-01-01' and '2008-12-01'
    and populacao.data = '2008-01-01' 
    GROUP BY estados.nome;

In this consultation I will sum up all populations of my municipalities and return the total by states, along with the number of deaths of the states. Follows the ER model: inserir a descrição da imagem aqui

  • How are the data from this date field in the table ?

  • It is as date in all tables... I put the ER model in question...

  • as far as I remember you can’t make 2 SUMS u Counts in different tables in the same query you’ll have to give a Union in two different and separate querys.

1 answer

0

Problem solved:

SELECT sum(populacao.quantidade),
    estados.nome, 
    (SELECT sum(internacao.quantidade)
  from estados as est
  inner join municipios as mun on (est.idEstado = mun.idEstado)
  inner join internacao on (mun.idMunicipio = internacao.idMunicipio)
  where internacao.data between '2008-01-01' and '2008-12-01'
  and est.nome = estados.nome
  GROUP BY est.nome) as internacao
from estados
inner join municipios on estados.idEstado = municipios.idEstado
inner join populacao on municipios.idMunicipio = populacao.idMunicipio
where populacao.quantidade  
and populacao.data = '2008-01-01' GROUP BY estados.nome;

Browser other questions tagged

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