How does this work in SQL sum(o.product_name='Bread') > 0,
e.g if the orders table (o) has product_name column such that the entry is Bread then will the condition
o.product_name='Bread' return 1 to the sum function and then the sum function will add all these ones ?
The Question is : There are 2 tables customers, orders. Find the customers who bought bread and milk but not eggs
Select c.customer_id , c.customer_name
FROM customers as c
left join
orders as o
on c.customer_id = o.customer_id
group by c.customer_id , c.customer_name
having
sum(o.product_name='Bread') > 0
and sum(o.product_name='Milk') > 0
and sum(o.product_name='Eggs') = 0
order by c.customer_name
Select c.customer_id , c.customer_name
FROM customers as c
left join
orders as o
on c.customer_id = o.customer_id
group by c.customer_id , c.customer_name
having
sum(o.product_name='Bread') > 0
and sum(o.product_name='Milk') > 0
and sum(o.product_name='Eggs') = 0
order by c.customer_name
As for your question, you need only those customers who bought both bread and milk but not eggs. I simply filters for the customers who bought both and then again do filtration to remove those who also bought eggs.