2

我正在尝试在 Access 中创建一个 SQL 查询,当 KEY 与三种非处方药(Motrin、Tylenol 和 Bayer)相关联时,它将返回所有字段(SELECT *)。在下面的示例中,将返回所有行,AMYZ32874并且不会返回任何行,WillyV32906因为他仅与 3 种药物中的 2 种相关联。

起始数据:

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);
4

2 回答 2

1

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

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
    );
于 2016-05-15T23:02:22.800 回答
0

您应该在子查询中放置相同的“WHERE”语句:

(SELECT Key FROM SAMPLEDB
WHERE OTC IN ('Tylenol', 'Mothrin', 'Bayer')
GROUP BY Key 
HAVING COUNT(Key) > 2)
于 2016-05-15T22:09:12.697 回答