dポイントプレゼントキャンペーン実施中!

下記のようなデータがあります。
col1 col2
==========
001 AAA
001 BBB
001 CCC
002 AAA
002 CCC
003 BBB
003 CCC
004 AAA

col2 にBBB を持たないレコードを抽出したいのですが
どのようにSQLを記述すればよいかご教授ください。

得たい結果
002
004

どうぞよろしくお願いいたします。

A 回答 (3件)

BBBを含むCol1を求めて、そのCol1をふくまない条件を指定すればよいです。




create table TableName
(
col1 varchar2(3),
col2 varchar2(3)
);


insert into TableName values('001', 'AAA');
insert into TableName values('001', 'BBB');
insert into TableName values('001', 'CCC');
insert into TableName values('002', 'AAA');
insert into TableName values('002', 'CCC');
insert into TableName values('003', 'BBB');
insert into TableName values('003', 'CCC');
insert into TableName values('004', 'AAA');

select distinct col1 from TableName
where col1 not in (
select col1
from TableName
where col2 = 'BBB'
)
order by col1;


COL1
----
002
004
    • good
    • 0
この回答へのお礼

どうも有り難うございました。

お礼日時:2011/02/17 09:11

select distinct col1


from テーブル t1
where not exists
( select 1 from テーブル t2
where t1.col1=t2.col1
and t2.col2 = 'BBB')

もありかと。
    • good
    • 0
この回答へのお礼

有難うございます。勉強になります。

お礼日時:2011/02/17 09:14

いろんな書き方があると思いますが、



select col1
from テーブル
group by col1
having count(case when col2='BBB' then 1 else null end) = 0;

とかでしょうか。
    • good
    • 0
この回答へのお礼

どうも有り難うございました。

お礼日時:2011/02/17 09:12

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