I have a table that has 2 columns that I’m concerned with
Business_ID / Product type
I am trying to write a SQL query to only get businesses that sell one type, but not the others. So the table is populated with
B_ID prod_type
123 | A
123 | A
123 | B
234 | A
234 | C
234 | C
456 | A
456 | D
789 | A
and the list goes on and on. I am trying to write a SQL statement that will find a B_ID that sells prod_type A and not prod_type B, C, D. Here is what I’m trying but it doesn’t work
SELECT phop_1.Business_id, phop_1.PRODUCT_TYPE, count(*)
FROM phop phop_1, phop phop_2
WHERE phop_1.Business_id = phop_2.Business_id
AND phop_1.PRODUCT_TYPE = 'A'
AND NOT phop_2.PRODUCT_TYPE = 'B'
GROUP BY phop_1.Business_id, phop_1.PRODUCT_TYPE
I also found how to exclude using an outer join, but since it’s the same table I can’t do that unless there is a way to select out the prod_type A before doing the join.
select phop_1.Business_id, phop_1.PRODUCT_TYPE, count(*)
from phop phop_1
LEFT OUTER JOIN phop phop_2
ON phop_1.Business_id = phop_2.Business_id
WHERE phop_2.Business_id IS NULL
GROUP BY phop_1.Business_id, phop_1.PRODUCT_TYPE
You can try something like this:
And the Fiddle.
Good luck.