Tuesday, November 25, 2008

Advanced Null Handling using the GROUP BY operator

As you may know,

select count(criteria) from junk
where criteria is null


and

select count(criteria) from junk
where criteria is not null


will always give you the same number. 10, in this case, irrespective of how many null values there exist in Column Criteria.

Therefore the problem would become clear if we needed to find the ratio of the number of null values for the following queries grouped by column 'FY' as below.

SELECT distinct count(case when decal is null then 0 else 1 end) as nulldecal,
Case
When [Date of Violation] Between '7/1/2005' AND '6/30/2006 23:59:59' then 'FY06'
When [Date of Violation]Between '7/1/2006' AND '6/30/2007 23:59:59' then 'FY07'
When [Date of Violation] Between '7/1/2007' AND '6/30/2008 23:59:59' then 'FY08'
else 'nulldate'
end as FY
from [ECB Violations]
where decal is null
group by
Case
When [Date of Violation] Between '7/1/2005' AND '6/30/2006 23:59:59' then 'FY06'
When [Date of Violation]Between '7/1/2006' AND '6/30/2007 23:59:59' then 'FY07'
When [Date of Violation] Between '7/1/2007' AND '6/30/2008 23:59:59' then 'FY08'
else 'nulldate'
end

No comments: