I'm using the following query to return a set of results to include zero counts:
Select rc.class, count(distinct(sa.sysurn)) as crimecount
from ReportClasses rc
left outer join sarscccodes sa
on rc.class = sa.ReportClass
where rc.class in ('HOMICIDE', 'RAPE', 'ROBBERY', 'AGGRAVATED ASSAULT', 'BURGLARY', 'BURG/THEFT FROM VEHI', 'OTHER THEFT')
group by class
order by class
This work as expected and return 0 counts for crime classes with no entries in the sarsccodes table:
class crimecount
AGGRAVATED ASSAULT 1
BURG/THEFT FROM VEHI 0
BURGLARY 3
HOMICIDE 0
OTHER THEFT 3
RAPE 0
ROBBERY 1
However, if I include a clause restricting the returns to entries within the sarscccodes table falling with a certain date range, the returned results exclude the categories with zero counts:
Select rc.class, count(*distinct(sa.sysurn)) as crimecount
from ReportClasses rc
left outer join sarscccodes sa
on rc.class = sa.ReportClass
where rc.class in ('HOMICIDE', 'RAPE', 'ROBBERY', 'AGGRAVATED ASSAULT', 'BURGLARY', 'BURG/THEFT FROM VEHI', 'OTHER THEFT')
AND sa.DateFrom > '2009-01-01'
group by class
order by class
class crimecount
AGGRAVATED ASSAULT 1
BURGLARY 1
OTHER THEFT 1
ROBBERY 1
Does anyone know how I can include the date clause and get zero returns?
Thanks,
Graeme.
by: mwvisa1Posted on 2009-11-05 at 21:25:26ID: 25756778
grum1,
) as crimecount
As soon as you add a WHERE condition on the table which was outer joined, you essential make the SQL statement equivalent to an inner join since nulls will be excluded for the direct comparison.
To get this to function correctly, move all "sa" criteria to the join expression.
Select rc.class, count(*distinct(sa.sysurn)
from ReportClasses rc
left outer join sarscccodes sa
on rc.class = sa.ReportClass
AND sa.DateFrom > '2009-01-01'
where rc.class in ('HOMICIDE', 'RAPE', 'ROBBERY', 'AGGRAVATED ASSAULT', 'BURGLARY', 'BURG/THEFT FROM VEHI', 'OTHER THEFT')
group by class
order by class
;
HTH
M-1