【问题标题】:How to exclude Customers who sold product A but not Product B如何排除销售产品 A 但不销售产品 B 的客户
【发布时间】:2021-03-11 16:37:05
【问题描述】:

我感觉很愚蠢,因为我无法思考如何写这个。

我们希望退回购买了产品 A 但未购买产品 B 的客户。B 通常与 A 一起购买,因此这是一个销售机会。

我从中提取的数据是订单项级别的订单数据。现在我只提取客户名称和产品,然后进行分组,以便按客户列出产品列表,结果如下所示:

PrimaryCustomer Product
Customer 1 Product A
Customer 1 Product B
Customer 1 Product C
Customer 2 Product A
Customer 2 Product C

我只需要退回客户 2,因为他们购买了产品 A,但没有购买产品 B。客户 1 购买了,所以我需要删除它们。

【问题讨论】:

标签: sql sql-server


【解决方案1】:

一种方法是聚合:

select PrimaryCustomer
from t
where product in ('A', 'B')
group by PrimaryCustomer
having max(product) = 'A';

这使用了产品的排序。那也许是作弊。因此,您可能会发现这更笼统:

having min(product) = max(product) and min(product) = 'A'

假设每个客户/产品有一行,您也可以使用not exists

select t.*
from t
where t.product = 'A' and
      not exists (select 1
                  from t t2
                  where t2.PrimaryCustomer = t.PrimaryCustomer and
                        t2.product = 'B'
                 );

这样做的好处是很容易从表中返回其他列。

【讨论】:

  • 我快接近了。我已经开始使用 NOT EXISTS 来处理它,但我没有正确使用内部的连接。谢谢!
【解决方案2】:

有很多方法可以实现这一点。其中:

select primarycustomer from mytable where product = 'Product A'
except
select primarycustomer from mytable where product = 'Product B'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-11
    • 2020-10-31
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    相关资源
    最近更新 更多