Pick up the name of the record in the most repeating column

0

I need to have the most repeated record appear in the tipo_doenca column from the localidade column, which is to display the disease that is in the greatest amount in that location.

Table name: TB_grafico

    
asked by anonymous 14.05.2018 / 18:39

3 answers

1

What else is repeated , is usually only one, so a limit goes well!

Example for location bangu

SELECT tipo_doenca, COUNT(tipo_doenca) FROM TB_grafico
where localidade='bangu'
GROUP BY tipo_doenca
ORDER BY COUNT(tipo_doenca) DESC
LIMIT 1;

Test Table

Result

Attherequestof@Sorack example in sqlfiddle.com

    
14.05.2018 / 19:28
3

You can simply group and sort to see what else is repeated

select tipo_doenca, count(tipo_doenca)
  from tb_grafico
 where localidade = 'Centro'
 group by tipo_doenca
 order by count(tipo_doenca) desc

EDIT as noted by @sorack, if you want to see all locations, you can add the location in select and group by . You also need to remove where and it would be nice to include order by to make it easier to see:

select localidade, tipo_doenca, count(tipo_doenca)
  from tb_grafico
 group by localidade, tipo_doenca
 order by localidade, count(tipo_doenca) desc
    
14.05.2018 / 18:59
0

You can create a VIEW that counts occurrences by location:

CREATE VIEW vw_ocorrencias AS (
  SELECT COUNT(1) AS ocorrencias,
         tg.localidade,
         tg.tipo_doenca
    FROM TB_grafico tg
   GROUP BY tg.localidade,
            tg.tipo_doenca
);

After that select only the data of the VIEW that do not have a divergent record with the greater amount:

SELECT vo.*
  FROM vw_ocorrencias vo
 WHERE NOT EXISTS(SELECT 1
                    FROM vw_ocorrencias vo2
                   WHERE vo2.localidade = vo.localidade
                     AND vo2.tipo_doenca <> vo.tipo_doenca
                     AND vo2.ocorrencias > vo.ocorrencias)
    
14.05.2018 / 18:53