Microsoft Access:2 条记录,根据特定条件排除 1 条

Microsoft Access: 2 records excluding 1 based on certain criteria

我有 1 个table。如果 ID 有多个记录,我想开发一个过滤掉 Dog 记录的查询。如果ID只有1条记录,则保留狗记录。

ID  | AnimalType
401 | Dog
401 | Cat
401 | Bird
402 | Dog
403 | Cat
404 | Dog
404 | Bird

查询结果将是...

ID | AnimalType
401| Cat
401| Bird
402| Dog
403| Cat
404| Bird

这是实现此目的的一种方法:

SELECT A.ID, A.AnimalType
FROM tblAnimals A
INNER JOIN ( SELECT ID, COUNT(1) as IDCount FROM tblAnimals GROUP BY ID ) T
  ON A.ID = T.ID
WHERE NOT (T.IDCount>1 and A.AnimalType='Dog')

基本思想是在子查询中获取记录的每个 ID 的计数,然后我们可以应用过滤掉大小写的确切逻辑 if "animal is a dog and there is more than one record for that ID".

Demo:http://www.sqlfiddle.com/#!6/db6a9/2(在SQL服务器,不是Access,但逻辑是一样的)

实现此目的的另一种方法是在您点击狗记录时使用 NOT EXISTS 函数来确定是否存在具有相同 ID 的任何其他动物:

SELECT ID, AnimalType
FROM Animals t1
WHERE AnimalType <> 'Dog' Or NOT EXISTS ( SELECT ID FROM Animals t2 WHERE t2.ID = t1.ID And AnimalType <> 'Dog' );