Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count data with mysql query

i have this following table

id   kelurahan    status
1    Pegambiran   Netral
2    Pegambiran   Netral
3    Kejaksan     Positif
4    Kesenden     Positif
5    Pegambiran   Negatif

i want to get result like this

kelurahan    count_positif   count_netral   count_negatif   total
Pegambiran   0               2              1               3
Kejaksan     1               0              0               1
Kesenden     1               0              0               1

i tried this query

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT kelurahan, 
(SELECT COUNT(status) FROM tbl_monitoring WHERE status = 'Positif' GROUP BY kelurahan LIMIT 1) AS count_positif, 
(SELECT COUNT(status) FROM tbl_monitoring WHERE status = 'Netral' GROUP BY kelurahan) AS count_netral,
(SELECT COUNT(status) FROM tbl_monitoring WHERE status = 'Negatif' GROUP BY kelurahan) AS count_negatif, 
COUNT(kelurahan) AS total 
FROM tbl_monitoring GROUP BY kelurahan

i get the result like this

enter image description here

any help would be appreciated, thanks.

>Solution :

  1. You should use SUM, not COUNT.
  2. Tested on dbfiddle
SELECT 
  kelurahan, 
  SUM(CASE WHEN status = 'Positif' THEN 1 ELSE 0 END) AS count_positif,
  SUM(CASE WHEN status = 'Netral' THEN 1 ELSE 0 END) AS count_netral,
  SUM(CASE WHEN status = 'Negatif' THEN 1 ELSE 0 END) AS count_negatif,
  SUM(1) AS total
FROM tbl_monitoring
GROUP BY kelurahan;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading