选择与列表中的所有项目匹配的行组

2022-01-31 00:00:00 sql tsql sql-server relational-division

假设我有两张桌子:

cars – 汽车列表

carname | modelnumber | ...

passedtest – 包含汽车通过的所有测试:

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 |

现在,我如何从 passedtest 表中选择通过所有测试(A、B、C、D)的汽车?

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

我尝试了 IN 语句,但它也匹配通过了一项测试的汽车.我正在寻找一个语句来匹配列表中所有行的 all 值.

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.

推荐答案

这个怎么样?

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

您也可以将它用作从 cars 表中获取信息的内部语句:

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
)

相关文章