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

时间:2018-11-12 19:28:10

标签: sql sqlite self-join

试图弄清楚如何同时订购A和B的客户的查询时遇到麻烦

enter image description here

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

5 个答案:

答案 0 :(得分:2)

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

我通常不会将代码仅作为答案,但是单词可以添加的内容不多-查询主要是对自身的解释

您也可以

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)

答案 1 :(得分:0)

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

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'
       )

答案 2 :(得分:0)

Select customerid from table group by customerid having product like 'A' and product like 'B'或 您可以尝试having count(distinct product) =2,这似乎更准确。 整个想法是在一组customerid中,假设1如果我有几个A,而B的count(唯一乘积)将为2,否则为1,因此答案如上所述。

答案 3 :(得分:0)

我将使用带有%load_ext sql %sql sqlite:// %%sql CREATE TABLE Store (Store_ID, Store Location, Opening_Year) * sqlite:// Done. %%sql ALTER TABLE Store DROP Store Location * sqlite:// (sqlite3.OperationalError) near "DROP": syntax error [SQL: 'ALTER TABLE Store DROP Store Location'] (Background on this error at: http://sqlalche.me/e/e3q8) 子句的相关子查询,以在单个HAVING子句中同时挖掘两种产品。

WHERE

答案 4 :(得分:0)

我刚想出的另一种方式是

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
相关问题