プロが教えるわが家の防犯対策術!

下記の場合で検索時にtagがaかつbを持つnoを返したい場合どのようなSQLを記述すれば良いのでしょうか。この場合だと1と3が返ってくるようにしたいです。
-----------
no | tag
-----------
1 | a
1 | b
1 | c
2 | b
2 | c
3 | a
3 | b
-----------

A 回答 (2件)

select no


from t
group by no
having count(case when tag = 'a' then 1 else null end) > 0
and count(case when tag = 'b' then 1 else null end) > 0

とかでもいいと思います。
no,tagで一意にならないときでも大丈夫なはずです。
    • good
    • 0
この回答へのお礼

だいぶおそくなりましたがありがとうございます。
皆様のお陰で少しですが、成長しました。

お礼日時:2012/11/04 01:33

noとtagの組み合わせがユニークかどうかにもよります。


一応こんな感じで

select no from hoge
where
tag in ('a','b')
group by no
having count(distinct tag)=2;

もしくは

select distinct h1.no from hoge as h1
inner join hoge as h2
on h1.no=h2.no
and h1.tag='a'
and h2.tag='b';
    • good
    • 0
この回答へのお礼

ありがとうございます。
上のはシンプルでわかりやすいです。

お礼日時:2012/11/04 01:36

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!