Sql - 排除0值

时间:2018-02-28 01:11:27

标签: mysql sql phpmyadmin

我执行此查询

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

2 个答案:

答案 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()

的案例表达式时,可以省略“else null”