-- 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
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;
2条答案
按热度按时间slsn1g291#
如果我对你的理解是正确的,你的信息非常有限,下面是解决办法。我把它撕成碎片,让你更好地理解它
z5btuh9x2#
如果有一个表包含客户ID和产品ID,则可以使用聚合:
也就是说,让客户谁没有订购的产品之一。
请注意,“一起排序”意味着它们的顺序相同。但是,您的数据不提供有关订单或购买时间的任何信息。