Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting Null values in MYSQL

Tags:

null

mysql

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?

like image 298
KoolKabin Avatar asked Aug 02 '10 13:08

KoolKabin


People also ask

Does MySQL COUNT NULL values?

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.

Does COUNT () COUNT NULL values?

COUNT(expression) does not count NULL values.

How do I find NULL records in MySQL?

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.


2 Answers

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
like image 183
dcp Avatar answered Sep 24 '22 08:09

dcp


null -> is null?

like image 26
foret Avatar answered Sep 25 '22 08:09

foret