获得购买2个产品的所有客户

时间:2014-02-10 10:45:24

标签: mysql sql

我有以下'简单'数据集

Customer  product    qty

A           p1        1
A           p2        1
B           p1        1
B           p3        1
C           p1        1
D           p2        1
D           p1        1

我需要让所有购买了p1和p2的客户,结果将是A和D. 没有透视的mysql怎么办?

由于

2 个答案:

答案 0 :(得分:2)

我正在重复Alma的答案,因为我认为该答案附带的评论引入了不必要的混淆,答案本身并没有充分解决。

SELECT customer
     , COUNT(DISTINCT product) ttl -- DISTINCT is only necessary if (customer,product) is NOT unique
  FROM t
 WHERE product IN ('p1', 'p2')
 GROUP 
    BY customer
HAVING COUNT(*) = 2 -- where 2 is equal to the number of items in IN();

答案 1 :(得分:1)

如果你想要完全匹配(即严格p1p2而没有别的),那么:

SELECT
  Customer,
  COUNT(DISTINCT product) AS products_count
FROM 
  t
WHERE
  product IN ('p1', 'p2')
GROUP BY
  Customer
HAVING
  -- >=2 in case if you'll want to include other products, not only p1 and p2
  -- but p1 and p2 must present. Note, that IN() must be modified also
  products_count=2

UPD。 (编辑后) “至少”你需要为IN(或其中的值)添加一些额外条件 - 这是因为当前WHERE条件只会留下p1和{{1} }。