Let's say I have 2 tables:
If I wanted to display employees belonging to places 1, 2, or 3, I would write a query similar to:
SELECT DISTINCT e.id, e.name FROM Employee e JOIN EmpLocXref x ON x.employee_id = e.id WHERE x.location_id IN (1, 2, 3) ;
An example .
But what if I would like to list employees who belong only to places 1, 2, and 3? I understand that I can write something similar to:
SELECT e.id, e.name FROM Employee e JOIN EmpLocXref x ON x.employee_id = e.id WHERE x.location_id IN (1, 2, 3) GROUP BY e.id, e.name HAVING COUNT(*) = 3 ;
Example
Is there a better way to do this that doesn't include dynamic SQL?
EDIT: Fixed derp moment in second request. Added Fiddler examples.
source share