Which Customers Have Particular Products?
This section moves from any product to particular products. It is also going to introduce aggregate string concatenation, an operation that is unfortunately not part of the SQL standard. So every database has a different method—with SQL Server’s being the most arcane. Let’s start with the most popular products and the customers who purchase them.
Which Customers Have the Most Popular Products?
It is easy to get the list of the most popular products by using an aggregation query. Let’s ask a slight variation on this question: How many customers purchase the ten most popular products? As a further refinement, let’s ask how many customers purchase one, two, three, and so on of these products.
The following query uses a subquery to identify the most popular products. This subquery is used in the WHERE clause in the subquery:
SELECT cnt, COUNT(*) as households FROM (SELECT c.HouseholdId, COUNT(DISTINCT ol.ProductId...