Forum

Posted by Yugandhar, March 14, 2022, 12:28 p.m.

How to find the customer ID who didn't purchase Book using SQL

I have sales data Customer ID. Product 1. Pen 2. Pen 2. Book 3. Pen 3. Book Here customer 1 not purchased book. Using oracle sql i want to see results as 1. Tried using !='Book' but getting all 3 customer ids. Please suggest Thank you in advance

Answers

I'm not familiar with Oracle syntax, but I would try something like the following: with pen_purchasers as ( select customer_id from sales where Product = 'Pen' ), book_purchasers as ( select customer_id from sales where Product = 'Book' ) select p.customer_id from pen_purchasers p left outer join book_purchasers b on p.customer_id = b.customer_id where b.customer_id is null Basically, find all the pen purchasers, then all the book purchasers, and join the two parts together. If the 2nd id is null, it means they were present in the first table but not the second. This is effectively an "anti-join", which exists in some SQL dialects but is not ANSI standard. Note that this solution is specific to this question. If you're trying to do this in a more general way, it will likely get pretty complex.
SQLPad user avatar

Mike (228)

March 14, 2022, 1:56 p.m.

SELECT customer_id FROM sales WHERE customer_id NOT IN ( SELECT customer_id FROM sales WHERE product = 'Book' ) GROUP BY 1;
SQLPad user avatar

Leon (949)

March 14, 2022, 1:57 p.m.