Reputation: 27
I am trying to improve my SQL skills but it's really not easy. When I think I improved a bit I encounter a basic SQL problem and I can't move forward. I have two tables. The only column that they have in common is a column "order". I would like to select a client who has both products (it doesn't matter if these products he/she purchased in one order or more). In my example this client is no. 345:
My code looks like this but it doesn't really solve my problem, because it lists people who purchased one product or both products:
select t2.client, t1.product, t1.order
from table_1 t1
join table_2 t2 on t1.order = t2.order
where product in ('a', 'b')
order by t2.client
Upvotes: 0
Views: 29
Reputation: 1271111
Use aggregation:
select t2.client
from table_1 t1 join
table_2 t2
on t1.order = t2.order
where t1.product in ('a', 'b')
group by t2.client
having count(distinct t1.product) = 2;
Upvotes: 2