select advertismentid
from the_table
where categoryid in ('A', 'C')
group by advertismentid
having count(*) = 2;
SQLFiddle:http ://sqlfiddle.com/#!12/b94d6/1
这假定不能将相同的 categoryid 多次分配给相同的 advertismentid。它还将包括具有 A、C 和其他类别的广告。
如果您想要那些恰好具有A 类和 C 类的广告,您需要排除那些具有更多类别的广告:
select advertismentid
from the_table
where categoryid in ('A', 'C')
group by advertismentid
having count(*) = 2;
intersect
select advertismentid
from the_table
group by advertismentid
having count(*) = 2;
SQLFiddle: http://sqlfiddle.com/#!12/8901c/4
The SQLFiddle also has another solution using except
instead of intersect
If your DBMS is limited and you cannot use except
or intersect
, you can use this alternative:
select t1.advertismentid
from the_table t1
where t1.categoryid in ('A', 'C')
group by t1.advertismentid
having count(*) = 2
and count(*) = (select count(*)
from the_table t2
where t2.advertismentid = t1.advertismentid)