Display a record by quantity and the most repeated value of a column

Asked

Viewed 116 times

0

Hello, I have the following problem: I need to display the localities, the number of shipments of each one (ie how often the name of the locality appears in the column) and the most common disease of each locality (that is, the name of the most common disease in that particular locality). inserir a descrição da imagem aqui

FOR EXAMPLE:

  • locality: Croatian¡ 1
  • Number of submissions: 4
  • most common disease: Conjunctivitis

I have these two query’s but they don’t work together, just one or the other

SELECT localidade, count(localidade) AS qt FROM tb_grafico group by localidade;

SELECT localidade, tipo_doenca, COUNT(tipo_doenca) as qtidade FROM tb_grafico
where localidade='Croatá 1'
GROUP BY tipo_doenca
ORDER BY COUNT(tipo_doenca) DESC
LIMIT 1;

preferably in a single sql querry

  • What have you tried to do? Read tour site, the idea is to help solve more specific questions ;)

  • yes I tried and got with two querry’s but when pulling the php data the first querry no longer worked

1 answer

0


My suggestion is that you create a VIEW totalling the amount based on locality and disease:

CREATE VIEW vw_grafico AS
  SELECT localidade,
         tipo_doenca,
         COUNT(localidade) AS quantidade
    FROM tb_grafico
   GROUP BY localidade,
            tipo_doenca;

After that make the selection of the biggest disease in vw_grafico:

SELECT g.*,
       (SELECT SUM(g3.quantidade)
          FROM vw_grafico g3
         WHERE g3.localidade = g.localidade) AS total
  FROM vw_grafico g
 WHERE NOT EXISTS(SELECT 1
                    FROM vw_grafico g2
                   WHERE g2.localidade = g.localidade
                     AND g2.tipo_doenca <> g.tipo_doenca
                     AND g2.quantidade > g.quantidade)
  • but it is exhibiting all the diseases of the neighborhood, I just wanted the locality, disease that most repeats and the amount to call in php and display only once

Browser other questions tagged

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