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.
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
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
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)