Access 数据库 - SQL,按同一列中的多个项目筛选

Access Database - SQL, Filtering by Multiple Items in Same Column

我正在尝试在 Access 中创建一个 SQL 查询,当 KEY 与三种非处方药(美林、泰诺和拜耳)相关联时,它将 return 所有字段 (SELECT *) .在下面的示例中,AMYZ32874 的所有行都将被 returned,而 WillyV32906 的行中的 none 将被 returned,因为他只与 2 关联3 种药物中的一种。

起始数据:

Key         Name      DOB       OTC
AmyZ32874   Amy Z     1/1/1990  Motrin
AmyZ32874   Amy Z     1/1/1990  Tylenol
AmyZ32874   Amy Z     1/1/1990  Bayer
WillyV32906 Willy V   2/2/1990  Motrin
WillyV32906 Willy V   2/2/1990  Tylenol
WillyV32906 Willy V   2/2/1990  Tylenol

期望的结果:

Key         Name      DOB       OTC
AmyZ32874   Amy Z     1/1/1990  Motrin
AmyZ32874   Amy Z     1/1/1990  Tylenol
AmyZ32874   Amy Z     1/1/1990  Bayer

我卡住了....这是我最近的尝试。

SELECT *
FROM SAMPLEDB
WHERE OTC IN ('Tylenol', 'Motrin', 'Bayer') and Key in
(SELECT Key FROM SAMPLEDB
GROUP BY Key HAVING COUNT (Key) > 2);

您应该在子查询中放入相同的 "WHERE" 语句:

(SELECT Key FROM SAMPLEDB
WHERE OTC IN ('Tylenol', 'Mothrin', 'Bayer')
GROUP BY Key 
HAVING COUNT(Key) > 2)

看起来有点难看,但我相信这应该可行:

SELECT 
  *
FROM 
  SAMPLEDB
WHERE 
  OTC IN ('Tylenol', 'Motrin', 'Bayer') 
  AND [Key] in
    (
      SELECT 
        [Key] 
      FROM 
        (
          SELECT 
            [Key]
            , OTC 
          FROM 
            SAMPLEDB
          WHERE 
            OTC IN ('Tylenol', 'Motrin', 'Bayer')
          GROUP BY 
            [Key]
            ,OTC 
        ) AS S1
      GROUP BY  
        [Key]
      HAVING 
        COUNT ([Key]) > 2
    );