SQL 查询 FILTER 多次购买同一产品且数量大于 5 的客户

SQL Query to FILTER customers who have purchased same product multiple times with a quantity greater than 5

我有一个 table Customer_Order_Data 包含这些列:

  1. customer_id
  2. order_id
  3. product_id
  4. 数量

我想通过 quantity > 5.

查找多次购买同一产品 (product_id) 的客户

假设我有以下数据 -

Order_id Customer_id product_id Quantity
00001 ABCD B019 2
00002 ABCD B019 6
00003 EFGH B018 8
00004 ABCD B019 7
00005 EFGH B018 1
00006 IJKL B017 9
00007 ABCD B015 10

我想在 quantity > 5 处过滤掉多次购买同一产品的客户。 现在 Customer EFGH 已经购买了 product B018 两次,但两次购买的数量都没有超过 5,因此不应显示在结果中。

预期结果 -

Order_id Customer_id product_id Quantity
00001 ABCD B019 2
00002 ABCD B019 6
00004 ABCD B019 7

一个选项使用子查询:

select t.*
from mytable t
where (
    select count(*) 
    from mytable t1 
    where 
        t1.customer_id = t.customer_id 
        and t1.product_id = t.product_id 
        and t1.quantity > 5
) > 1

想法是计算 table 中有多少行具有相同的客户和产品,并且数量大于 5。

您还可以使用 window 函数:

select *
from (
    select t.*,
        sum(case when quantity > 5 then 1 else 0 end) over(partition by customer_id, product_id) as cnt
    from mytable t
) t
where cnt > 1

您可以按如下方式使用IN子句:

Select * from your_table
Where (customer_id, product_id) IN 
(Select customer_id, product_id
  From your_table t
 Where quantity > 5
Group by customer_id, product_id
Having count(1) > 1)