我试图在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);
答案 0 :(得分: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
);
答案 1 :(得分:0)
您应该在子查询中添加相同的“WHERE”语句:
(SELECT Key FROM SAMPLEDB
WHERE OTC IN ('Tylenol', 'Mothrin', 'Bayer')
GROUP BY Key
HAVING COUNT(Key) > 2)