SQL查询以获取购买其他客户购买的产品的客户

时间:2020-05-01 01:47:04

标签: sql oracle

我有两个实体订单和订单项 订单捕获订单ID,客户ID和运输详细信息 订单项详细信息将捕获订单ID,订购的产品和数量。

我想获得与其他购买者同时购买了相同产品的customer_id。

select corder.customer_id,lineitem.prod_id
from lineitem
join corder on corder.order_id=lineitem.order_id
where prod_id in(select prod_id from lineitem
group by prod_id
having count(prod_id)>2)

此查询获取客户ID和产品,我还需要仅过滤仅由其他三个客户购买产品的客户

1 个答案:

答案 0 :(得分:0)

您希望由四个或更多客户购买的产品。那是:

select li.prod_id
from lineitem li join
     corder o
     on li.order_id = o.order_id
group by li.prod_id
having count(distinct o.customer_id) >= 4;

现在,您希望购买这些产品的客户。所以:

select distinct c.customer_id
from corder co join
     lineitem li
     on li.order_id = o.order_id
where li.prod_id in (select li.prod_id
                     from lineitem li join
                          corder o
                          on li.order_id = o.order_id
                     group by li.prod_id
                     having count(distinct o.customer_id) >= 4
                    );