I have the following SQL statement:
SELECT r.Result AS Resuly,
COUNT(f.fieldID) AS [Count]
FROM dbo.Fields f
RIGHT JOIN dbo.Results r ON f.Results = r.ID
WHERE f.RegionID = @RegionID
GROUP BY r.Result
What I Would like to statement to do is return all the different results (weither they have a count in the Field DB or not). Currently the Query only returns the values that have a count.
ie in the reuslts DB I have
ID 1, 2 and 3
Result x, y, z
only x and z have field that require this result in the field DB so I only get back
Result x, z
count 1, 2
what I want is
Result x,y,z
Count 1,(null or 0), 2
That’s because your
whereclause is filtering out results with no fields.The
whereclause is applied after the join is made; criteria in theONclause is applied before the JOIN is made.The [conceptual] process for executing a SQL
selectquery is:fromclause.group byclause, if it exists.havingclause, if such exists.order byclause, if such exists.compute/compute byclauses, if such exists.So…you need to do this to get what you want:
The above will give you one row for every result, with a count of matching fields in the specified region (what I believe is what you’re asking for). The count will be zero for any result with no matching fields in the specified region.