SQL 查询同时订购了产品 A 和 B 的客户 ID

SQL querying a customer ID who ordered both product A and B

在尝试弄清楚如何return查询同时订购了 A 和 B 的客户时遇到了一些麻烦

我要查找的是所有同时订购了产品 A 和产品 B 的客户

我从未使用过 SQLite,但由于它的规格说明它是一个关系数据库,它应该允许以下查询。

select CustomerID
  from table t
 where exists (
       select *
         from table
        where CustomerID = t.CustomerID
          and Product  = 'A'
       )
   and exists (
       select *
         from table
        where CustomerID = t.CustomerID
          and Product  = 'B'
       )

Select customerid from table group by customerid having product like 'A' and product like 'B' 或 你可以试试having count(distinct product) =2这似乎更准确。 整个想法是在一组 customerid 假设 1 如果我有几个 A 和 B 的计数(不同的产品)将给出 2 否则它将是 1 所以答案如上。

我将使用带有 HAVING 子句的相关子查询在单个 WHERE 子句中获取两种产品。

SELECT
  t.Customer
FROM
  @t AS t
WHERE
  EXISTS
    (
      SELECT
        1
      FROM
        @t AS s
      WHERE
        t.Customer = s.Customer
        AND s.Product IN ('A', 'B')
      HAVING
        COUNT(DISTINCT s.Product) = 2
    )
GROUP BY
  t.Customer;
SELECT CustomerID 
FROM table
WHERE product in ('a','b')
GROUP BY customerid
HAVING COUNT(distinct product) = 2

我通常不会 post 只用代码回答问题,但没有太多的文字可以添加到这个问题中——查询主要是自我解释

你也可以

HAVING max(product) <> min(product)

可能值得指出的是,在查询中,执行 WHERE,过滤到产品 A 和 B。然后执行 GROUP BY,对客户分组并计算产品的不同数量(或获取最小和最大限度)。然后执行 HAVING,过滤到仅具有 2 个不同产品的产品(或仅获取 MIN 即 A 与 MAX 即 B 不同的产品)

如果您从未遇到过 HAVING,它在逻辑上等同于:

SELECT CustomerID
FROM(
    SELECT CustomerID, COUNT(distinct product) as count_distinct_product
    FROM table
    WHERE product in ('a','b')
    GROUP BY customerid
)z
WHERE
     z.count_distinct_product = 2

在 HAVING 子句中,您只能引用分组依据中提到的列。还可以参考group by

中没有提到的其他列的聚合操作(比如count/min/max)

我刚刚想到的另一种方法是

SELECT CustomerID 
FROM table
WHERE product in ('a','b')
GROUP BY customerid
HAVING sum(case product ='a' then 1 else 0 end) > 0
    and sum(case when product ='b' then 1 else 0 end) > 0