The prompt is Assume Risk “1” facilities are required to have at least 3-type inspections per year. Display the facilities that failed to meet this requirement in 2013 AND that had at least 1 Failed Canvass-type inspection.Show the facility name and how many Canvass inspections it had in 2013. HINT: use a subquery
So this is my code
SELECT DBAName, COUNT(*)
FROM FoodInspectionOriginal, Organization
WHERE Risk = 1 AND [Inspection Type] IN (SELECT [Inspection Type] FROM FoodInspectionOriginal WHERE [Inspection Type] = 'Canvass' AND [Inspection Date] = Year(2013))
GROUP BY DBAName;
And I am getting this is the output
Msg 209, Level 16, State 1, Line 3
Ambiguous column name 'Risk'.
I would just use aggregation. Assuming the following table structure for table foodinspectionoriginal
:
dbaname -- name of the facility
inspection_date
inspection_type -- "Canvass", ...
inspection_status -- "successful", "failed"
The query could be phrased as follows:
select dbaname,
sum(case when inspection_type = 'Canvass' and inspection_status = 'failed' then 1 else 0 end) as cnt_failed_canvass
from foodinspectionoriginal
where
risk = 1
and inspection_date >= '20130101'
and inspection_date < '20140101'
group by dbaname
having
count(*) < 3
and sum(case when inspection_type = 'Canvass' and inspection_status = 'failed' then 1 else 0 end) > 0