Select group of rows that match all items in a list

user1229351 picture user1229351 · Apr 12, 2013 · Viewed 72.3k times · Source

Assume I have two tables:

cars – list of cars

carname | modelnumber | ...

passedtest – contains every test that a car passed:

id | carname | testtype | date | ...
1  | carA    | A        | 2000 |
2  | carB    | C        | 2000 |
3  | carC    | D        | 2001 |
4  | carA    | C        | 2002 |

Now, how can I select a car from the passedtest table that passed all tests (A, B, C, D)?

I tried the IN statement but it also matches cars that pass even one test. I am looking for a statement to match all values in a list across all rows.

Answer

MarcinJuraszek picture MarcinJuraszek · Apr 12, 2013

How about this?

SELECT carname
FROM PassedTest
GROUP BY carname
HAVING COUNT(DISTINCT testtype) = 4

You can also use it as an inner statement for taking info from the cars table:

SELECT *
FROM cars
WHERE carname IN (
    SELECT carname
    FROM PassedTest
    GROUP BY carname
    HAVING COUNT(DISTINCT testtype) = 4
)