I have a problem. I have a SQL-database named customers
with the 3 columns Country
, CustomerID
and Product
. With that database, I want to count all the customers which bought the products bike, flask and helmet but grouped by the country as you can see in the following picture.
Is there a chance you can help me out with that? I guess I have to make a join on the same table and make a nested query with another select, but I don’t really know how to do that.
I would be very thankful for your help!
Advertisement
Answer
You have to do aggregation in two steps. First find the customers with the 3 different products, then count these customers.
SELECT country, count(*) FROM ( SELECT country, CustomerID FROM customers WHERE product IN ('Bike','Flask','Helmet') GROUP BY country, CustomerID HAVING COUNT(distinct product) = 3 ) dt GROUP BY country