Skip to content
Advertisement

SQL customer who never order product p1 and p2 together

I do have two table. I want to find customers who never order product p1 and p2 together(there are million rows in this table)

customer_id  2,4,1,4,2,1,3,2,1   

product_id.  p1,p3,p2,p1,p2,p3,p4,p2

Advertisement

Answer

If I understand you correctly, with your very limited information, here is the solution. I broke it up to pieces, for you to understand it better

-- to get customers who ordered P1 
Select customer_id from tbl where product_id = 'P1'

-- to get customers who ordered P2
Select customer_id from tbl where product_id = 'P2'

-- to get customers who ordered both P1 & P2
Select customer_id from tbl p1 
inner join tbl p2 on p1.customer_id = p2.customer_id 
where p1.product_id = 'P1' and p2.product_id = 'P2'

-- to get customers who did not ordered both P1 & P2 together
Select * from tbl m
Left Join
(
Select customer_id from tbl p1 
inner join tbl p2 on p1.customer_id = p2.customer_id 
where p1.product_id = 'P1' and p2.product_id = 'P2'
) q on m.customer_id = q.customer_id
Where q.customer_id is null
Advertisement