我在SQL Access中有下表,我想找出哪些产品有2个不同的类别。
例如,产品abc
只有一个类别,所以我不希望它显示在我的查询中,但产品def
同时具有两个类别,所以我希望它显示。
+----+---------+----------+
| ID | Product | Category |
+----+---------+----------+
| 1 | abc | A |
| 2 | abc | A |
| 3 | def | B |
| 4 | def | A |
| 5 | abc | A |
+----+---------+----------+
答案最终取决于您是在寻找分配给多个类别的产品,还是您在问题中陈述的正好 2 个类别:
我想找出哪些产品有2 个不同的类别。
对于后者,您可以使用如下所示的内容:
select t.product
from (select distinct product, category from YourTable) t
group by t.product
having count(*) = 2
对于前者,有许多可能的选项 - 您只需将上述查询中的相等运算符=
更改为大于或等于运算符>=
即可产生:
select t.product
from (select distinct product, category from YourTable) t
group by t.product
having count(*) >= 2
或者,您可以使用where exists
子句来测试分配给不同category
的同一product
是否存在至少一条其他记录:
select distinct t.product
from YourTable t
where exists
(select 1 from YourTable u where u.product = t.product and u.category <> t.category)
或者,您可以根据 @forpas 建议的查询,在having
子句中将聚合与min/max
测试一起使用。
在上述所有示例中,将YourTable
更改为表的名称。
Access 不支持COUNT(DISTINCT ...)
因此对于示例数据,HAVING
子句可以设置最小类别与最大类别不同的条件:
select Product
from tablename
group by Product
having min(Category) <> max(Category)