我正在使用ACCESS 2010中的SQL查询,我有一个看起来像这样的表:
Mytable
ID | TYPE
1 | a
1 | b
2 | a
2 | a
3 | a
3 | b
3 | c
我想要返回与每个ID匹配的所有类型至少一次。
因此,在这种情况下,只会返回a
,因为它是1
,2
和3
行所代表的唯一类型。
非常感谢!
答案 0 :(得分:0)
在常规SQL中,您可以编写:
select type
from mytable
group by type
having count(distinct id) = (select count(distinct id) from mytable);
这在MS Access中不起作用,因为Access不支持COUNT(DISTINCT)
。
但是,如果我们假设mytable
中没有重复项,则此变体应该有效:
select type
from mytable
group by type
having count(*) = (select count(*)
from (select distinct id from mytable) as t
);
编辑:
如果表可能包含重复项,则可以在聚合之前删除它们:
select type
from (select distinct type, id from mytable ) as ti
group by type
having count(*) = (select count(*)
from (select distinct id from mytable) as t
);
答案 1 :(得分:0)
这是你接近它的一种方式;子查询返回至少两次出现的所有ID,然后您加入这些ID所存在的所有值。
SELECT a.ID, b.TYPE
FROM
(
SELECT ID
FROM Mytable
GROUP BY ID
HAVING COUNT(ID) > 1
) a
INNER JOIN Mytable b ON b.ID = a.ID