t-sqlsql-server-2012-express

T-SQL select all IDs that have value A and B


I'm trying to find all IDs in TableA that are mentioned by a set of records in TableB and that set if defined in Table C. I've come so far to the point where a set of INNER JOIN provide me with the following result:

TableA.ID | TableB.Code
-----------------------
1         | A
1         | B
2         | A
3         | B

I want to select only the ID where in this case there is an entry for both A and B, but where the values A and B are based on another Query. I figured this should be possible with a GROUP BY TableA.ID and HAVING = ALL(Subquery on table C). But that is returning no values.


Solution

  • Since you did not post your original query, I will assume it is inside a CTE. Assuming this, the query you want is something along these lines:

    SELECT ID
    FROM cte
    WHERE Code IN ('A', 'B')
    GROUP BY ID
    HAVING COUNT(DISTINCT Code) = 2;