Within my application, I have a set of filters that can be applied when listing resources, which builds up a query by adding WHERE clauses, etc. before executing the query. This is using SQL Server 2008.
I have two pertinent tables, one which contains some static data about the resource, and another which can contain arbitrary/optional fields pertaining to that resource.
First table is something like this (table names & fields changed):
CREATE TABLE Resources (
ResID varbinary(28),
... extra stuff omitted
type integer );
The second table just has name/value pairs and the corresponding resource ID
CREATE TABLE ResourceFields (
ResID varbinary(28) NOT NULL,
Name nvarchar(255) NOT NULL,
Value nvarchar(1024) NOT NULL);
So, for this example, there could be multiple rows in ‘ResourceFields’ with name = ‘ContactName’ for the same ResID.
What I want to do is get a count of the number of rows in the ‘Resources’ table that have more than one ‘ContactName’ listed in ‘ResourceFields’ with ‘type’ equal to some value.
I came up with this (don’t laugh — I know just enough SQL to cause problems)
SELECT count(r.ResID)
FROM Resources as r
INNER JOIN ResourceFields AS rf
ON rf.ResID = r.ResID
AND rf.name = 'ContactName'
WHERE r.type = 1
GROUP BY rf.ResID
HAVING COUNT(rf.Value) > 1;
but instead of returning the count of the number of rows (43 in my test set) in ‘Resources’, I get all the COUNT(rf.Value) values returned (that is, 43 individual counts).
What am I doing wrong?
Just use your original query as a derived table (put it in a subselect):