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.
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
)