SELECT NAMA_DUN,
COUNT(case when ((RIGHT(noMyKid, 1))% 2) = 0 then 1 else 0 end) AS FEMALE,
COUNT(case when ((RIGHT(noMyKid, 1))% 2) = 1 then 1 else 0 end) AS MALE,
COUNT(DISTINCT(noMyKid)) as jumlah
FROM mohon
LEFT JOIN dun ON dun.KOD_DUN=mohon.dun_nama
WHERE status_proses = 'diproses'
AND concat('20', substr(noMyKid, 1, 2)) = '2008'
AND status_mohon = 'Layak'
AND status_semak = '1'
AND (
status_bayar = ''
OR status_bayar = 'Belum'
OR status_bayar = 'Sudah')
AND (
status_terima = ''
OR status_terima = 'Terima'
) GROUP BY dun_nama
ORDER BY NAMA_DUN
这是我的mysql代码。为什么我的“COUNT CASE WHEN”为女性和男性专栏提供相同的输出。
答案 0 :(得分:2)
通常COUNT()
用于计算行数,因此通常以COUNT(*)
的形式使用。当您使用字段(或其他任何内容)作为COUNT()
的参数时,对于每个无NULL
值,它都会计为1。
在您的情况下,您的所有值都不是NULL
(它们是1或0),因此您最终会得到相同的结果。
所以Abhik Chakraborty是对的,使用SUM()
,一切都应该没问题。
答案 1 :(得分:1)
COUNT()
函数只识别非空值,因此当使用像这里一样的case表达式时,可以在需要的地方显式返回NULL
SELECT NAMA_DUN,
COUNT(case when ((RIGHT(noMyKid, 1))% 2) = 0 then 1 else NULL end) AS FEMALE,
COUNT(case when ((RIGHT(noMyKid, 1))% 2) = 1 then 1 else NULL end) AS MALE,
COUNT(DISTINCT(noMyKid)) as jumlah
OR,通过忽略else条件隐式返回NULL
SELECT NAMA_DUN,
COUNT(case when ((RIGHT(noMyKid, 1))% 2) = 0 then 1 end) AS FEMALE,
COUNT(case when ((RIGHT(noMyKid, 1))% 2) = 1 then 1 end) AS MALE,
COUNT(DISTINCT(noMyKid)) as jumlah
OR,使用SUM()模拟计数的效果,前提是你使用1和0(或1和NULL)
SELECT NAMA_DUN,
SUM(case when ((RIGHT(noMyKid, 1))% 2) = 0 then 1 else 0 end) AS FEMALE,
SUM(case when ((RIGHT(noMyKid, 1))% 2) = 1 then 1 else 0 end) AS MALE,
COUNT(DISTINCT(noMyKid)) as jumlah