How do i count null values while making cross tab query?
I have a table with three colums [id, name, answer]
i have following records:
ID NAME ANS
1 ABC 1
1 ABC 0
1 ABC NULL
2 XYZ 1
2 XYZ NULL
2 XYZ NULL
2 XYZ 1
2 XYZ 0
1 ABC 0
now i would like to get my result:
ID Name NULLCOUNT TRUE COUNT FALSE COUNT
1 ABC 1 1 2
2 XYZ 2 2 1
I am using following SQL Statement:
select ID, NAME,
sum(case ANS when null then 1 else 0 end) as NULLCOUNT,
sum(case ANS when 1 then 1 else 0 end) as TRUECOUNT,
sum(case ANS when 0 then 1 else 0 end) as FALSECOUNT
from
TBL1
Group By ID, Name
Getting my result:
ID Name NULLCOUNT TRUE COUNT FALSE COUNT
1 ABC 0 1 2
2 XYZ 0 2 1
The NULL Count is getting error. Why and how can i solve this?
Introduction to MySQL count() The MySQL COUNT() function provides a number of records in the result set from a table when an SQL SELECT statement is executed. This function does not count the NULL values.
COUNT(expression) does not count NULL values.
To look for NULL values, you must use the IS NULL test. The following statements show how to find the NULL phone number and the empty phone number: mysql> SELECT * FROM my_table WHERE phone IS NULL; mysql> SELECT * FROM my_table WHERE phone = ''; See Section 3.3.
I believe instead of this:
sum(case ANS when null then 1 else 0 end) as NULLCOUNT
You should use this:
sum(case when ANS is null then 1 else 0 end) as NULLCOUNT
null -> is null?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With