SELECT wilayah,nilai,t_rkpd,tahun,periode
FROM nilai_indikator
INNER JOIN provinsi ON nilai_indikator.wilayah=provinsi.id
WHERE tahun='2022' AND periode='08' AND id_indikator='6'
When i query that code the result is like this
table
I try count if the nilai
is less or greater than t_rkpd
, using this code:
SELECT COUNT(CASE WHEN nilai > t_rkpd THEN 1 END) AS tercapai
FROM nilai_indikator
INNER JOIN provinsi ON nilai_indikator.wilayah=provinsi.id
WHERE tahun='2022' AND periode='08' AND id_indikator='6'
SELECT COUNT(CASE WHEN nilai < t_rkpd THEN 1 END) AS tidak_tercapai
FROM nilai_indikator
INNER JOIN provinsi ON nilai_indikator.wilayah=provinsi.id
WHERE tahun='2022' AND periode='08' AND id_indikator='6'
But the result both of them is 0, it should be 34 when nilai
greater then t_rkpd
. why this is happening?
3
Answers
Try the same code using SUM instead of Count and let me know if it works.
And you need to group by some column as there is an aggregate. Do let me know if this helps
Assuming that NULL means 0. You just need to add a condition..
NULL means "unknown value". So, if you compare nilai with t_rkpd and one of the values is NULL then the answer is "unknown".
You have
COUNT(CASE WHEN nilai > t_rkpd THEN 1 END)
. TheTHEN
part gets executed when the expressionnilai > t_rkpd
is true. There is noELSE
in the expression, so the DBMS defaults toELSE NULL
. This part gets executed whennilai > t_rkpd
is not true, namely false or unknown.This means, when nilai or t_rkpd are null, you get a null as an expression result, and
COUNT
ignores this row hence.In the following query we consider all rows and all comparison results: