从不同时订购产品p1和p2的sql客户

anauzrmj  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(233)

我有两张table。我想找到从不同时订购产品p1和p2的客户(此表中有一百万行)

customer_id  2,4,1,4,2,1,3,2,1   

product_id.  p1,p3,p2,p1,p2,p3,p4,p2
slsn1g29

slsn1g291#

如果我对你的理解是正确的,你的信息非常有限,下面是解决办法。我把它撕成碎片,让你更好地理解它

-- to get customers who ordered P1 
Select customer_id from tbl where product_id = 'P1'

-- to get customers who ordered P2
Select customer_id from tbl where product_id = 'P2'

-- to get customers who ordered both P1 & P2
Select customer_id from tbl p1 
inner join tbl p2 on p1.customer_id = p2.customer_id 
where p1.product_id = 'P1' and p2.product_id = 'P2'

-- to get customers who did not ordered both P1 & P2 together
Select * from tbl m
Left Join
(
Select customer_id from tbl p1 
inner join tbl p2 on p1.customer_id = p2.customer_id 
where p1.product_id = 'P1' and p2.product_id = 'P2'
) q on m.customer_id = q.customer_id
Where q.customer_id is null
z5btuh9x

z5btuh9x2#

如果有一个表包含客户ID和产品ID,则可以使用聚合:

select customer_id
from t
group by customer_id
having sum(case when product_id = 'P1' then 1 else 0 end) = 0 or
       sum(case when product_id = 'P2' then 1 else 0 end) = 0;

也就是说,让客户谁没有订购的产品之一。
请注意,“一起排序”意味着它们的顺序相同。但是,您的数据不提供有关订单或购买时间的任何信息。

相关问题