Counting NULL values ​​in MYSQL

How can I count null values ​​when doing a cross tab request?

I have a table with three columns [id, name, answer]

I have the following entries:

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 the 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 number gets an error. Why and how can I solve this?

+5
source share
3 answers

Instead, I believe:

 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
+7
source

null → null?

+1
source

NULL , "CASE WHEN ANS NULL" ( GROUP BY). :

select ID, NAME, 
    sum(if(ans IS NULL, 1, 0)) 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
+1

All Articles