I have a table linking customers to previous purchases:
RecID CustID ProdID
1 20 105
2 20 300
3 31 105
4 45 105
5 45 300
6 45 312
I’d like to get a list of CustIDs that bought Item 105,
but did NOT but Item 300.
In this case, CustID 31.
I can’t seem to do it with selects and joins. I am stumped!
I sure would appreciate some help from experienced SQL folks.
Thank you!
Thanks!
I am the original author of the question.
Mark Byers second example with NOT IN works great! (I did not try others after this one worked for me).
His first example with LEFT JOIN did not return any CustIDs…I think I copied it correctly and used the proper table names and column names. So I don’t know why it did not work for me.
Thanks again to all who were so kind as to take the time to write out some SQL for me.
I had to create a new account to leave a comment (I could not login with the account where I created this yesterday, and the password recovery said it couldn’t find me)
There are three common approaches. Here is a LEFT JOIN approach:
Here is NOT IN:
Or you could use NOT EXISTS:
Which has better performance depends on which database and version you are using.
For SQL Server the best is to use either NOT IN or NOT EXISTS:
Source: