提问:get a list of customers who bought both A and B
SELECT CustomerID
FROM CustomerList
WHERE ProductID IN ('A', 'B')
GROUP BY CustomerID
HAVING COUNT(*) = 2
如果没有对ProductID每个强制执行唯一性CustomerID,DISTINCT则需要关键字,
SELECT CustomerID
FROM CustomerList
WHERE ProductID IN ('A', 'B')
GROUP BY CustomerID
HAVING COUNT(DISTINCT ProductID ) = 2
对于第二个问题,“..A and C and D but not B and E and F”
SELECT CustomerID
FROM CustomerList
WHERE ProductID IN ('A', 'C', 'D')
GROUP BY CustomerID
HAVING COUNT(*) = 3 AND
CustomerID NOT IN
(
SELECT CustomerID
FROM CustomerList
WHERE ProductID IN ('B','E','F')
)