First, the SQL Server query I’m using:
SELECT InfoSource
FROM dbo.orders
WHERE Price IS NULL
AND Date IS NULL
AND Expiry IS NULL
GROUP BY InfoSource
HAVING COUNT(InfoSource) = 1
Many records can have the same InfoSource
value. I am attempting to return the value of any InfoSource
where there is only and exactly one record that exists for that InfoSource
, and the WHERE
conditions are met within that one record.
The problem is, after I run this query, I take the results and do a SELECT
statement on them just to verify the records meet the conditions, but many of the InfoSource
values exist in more than one record. If there is more than one record for a given InfoSource
, the query should not be returning that InfoSource
at all regardless of the WHERE
conditions.
Do I somehow have my GROUP BY
and HAVING
misplaced?
Advertisement
Answer
the query should not be returning that InfoSource at all regardless of the WHERE conditions
At the present, the where
clause is executed before the having
clause.
What you need is for it to be executed after.
select * from
dbo.orders
WHERE Price IS NULL
AND Date IS NULL
AND Expiry IS NULL
AND InfoSource in (SELECT InfoSource
FROM dbo.orders
GROUP BY InfoSource
HAVING COUNT(InfoSource) = 1)