create table TableA(Customer_ID varchar(10), Product_Name varchar(10));
insert into TableA values('001' ,'A');
insert into TableA values('001' ,'B');
insert into TableA values('001' ,'C');
insert into TableA values('002' ,'A');
insert into TableA values('002' ,'B');
insert into TableA values('003' ,'A');
insert into TableA values('003' ,'C');
insert into TableA values('004' ,'A');
insert into TableA values('005' ,'B');
insert into TableA values('006' ,'C');
Query#1 (using in):
select * from TableA
where customer_id in (select customer_id from TableA where product_name='A')
and customer_id not in (select customer_id from TableA where product_name='C')
| Customer_ID |
Product_Name |
|---|
| 002 |
A |
| 002 |
B |
| 004 |
A |
Query#2 (using exists):
select * from TableA A
where exists (select 1 from TableA B where product_name='A' and A.customer_id=B.customer_id)
and not exists (select 1 from TableA C where product_name='C' and A.customer_id=C.customer_id)
Output:
| Customer_ID |
Product_Name |
|---|
| 002 |
A |
| 002 |
B |
| 004 |
A |
db<>fiddle here