我执行此查询
SELECT Kd_penyakit, Penyakit,
COUNT(case when Kd_gejala in ('G01','','G03','G04','','','','','','','','','','','','','','','','','','')then 1 else null end) / COUNT(kd_penyakit)*100 AS cases
FROM tbl_casebase
GROUP BY Kd_penyakit
ORDER BY cases DESC
,结果就像这样
Kd_penyakit Penyakit cases
P01 Tipus Ayam 42.8571
P06 Produksi Telur 25.0000
P03 Salesma Ayam 14.2857
P02 Berak Darah 0.0000
P04 Gumboro 0.0000
P05 Mareks 0.0000
我的问题是如何排除0值,结果就像这样
Kd_penyakit Penyakit cases
P01 Tipus Ayam 42.8571
P06 Produksi Telur 25.0000
P03 Salesma Ayam 14.2857
答案 0 :(得分:0)
一种方法是使用相同的表达式
在HAVING
子句中对其进行过滤
SELECT ...
FROM ...
GROUP BY ...
HAVING COUNT(case when Kd_gejala in ('G01','','G03','G04','','','','','','','','','','','','','','','','','','')then 1 else null end) / COUNT(kd_penyakit)*100 > 0
ORDER BY ...
由于您使用的是mysql,因此可以使用ALIAS
编写它,尽管它不是标准做法,只能在mysql中使用,并且ONLY_FULL_GROUP_BY extension被废除。
SELECT ...
FROM ...
GROUP BY ...
HAVING cases > 0
ORDER BY ...
答案 1 :(得分:0)
使用exists
:
SELECT Kd_penyakit, Penyakit,
COUNT(case when Kd_gejala in ('G01','G03','G04','') then 1 end) / COUNT(kd_penyakit)*100 AS cases
FROM tbl_casebase
where exists (
select 1 from tbl_casebase t2
where tbl_casebase.Kd_penyakit = t2.Kd_penyakit
and t2.Kd_gejala in ('G01','G03','G04','')
)
GROUP BY Kd_penyakit
ORDER BY cases DESC
;
注意,在使用带有count()