tags:

views:

74

answers:

3

hi,

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?

+6  A: 

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
dcp
thnx it worked but want to ask why its different than truecount and falsecount. Shouldn't it be as same for truecount and falsecount? Which one is correct for rest others too
KoolKabin
null is like undefined. Undefined != undefined.
foret
@KoolKabin: because you are implicitly comparing ANS and NULL in the `case` construct. However, NULL doesn't equal anything, not even itself: `NULL != NULL` (evaluates to true). You need to use the special "IS NULL" construct: `NULL IS NULL` (evaluates to true). Tricky, yes. Useful, also yes.
Piskvor
@KoolKabin - "Which one is correct for rest others too" - I think your other 2 case statements are ok, you just had a mistake on the null check. As foret correctly points out, null != null, which is why you must always use the "is null" syntax when checking for null.
dcp
+1  A: 

null -> is null?

foret
how can i use it in my solution. plz explain
KoolKabin
It is repeat of dcp's answer. Seems like we wrote it almost simultaneously.
foret
A: 

NULL doesn't even compare with itself, you could use "CASE WHEN ANS is NULL"(you're also missing GROUP BY). Or try:

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
nos
sorry for missing it in question but in fact i was using it in my query. i will be editing it in my question too.. thnx for suggestion
KoolKabin