[英]MySQL: How to find products repeatedly ordered by customers in different orders
[英]Find products which customers ordered multiple times
有一个mysql表,用于存储在线商店的订购商品。 表格中最重要的字段:
order_item_id
product_id
order_id
customer_email
(来自联接表) 我想找到相同的顾客一次又一次订购的产品。 基本上,我们只需要订购多次的客户。 对于这些用户,我想检查是否订购了不止一次的产品。 例如,通常您只订购一次激光打印机,但是以后再订购碳粉。 当客户至少订购两次碳粉时,我需要提供信息,以检查哪些产品需要多次购买,或者对产品如此满意,以至于第二次订购。 我是否需要一些GROUP BY
或子查询?
您可以尝试通过计数> 1来使用组
select product_id, customer_email , count(*)
from my_table
group by product_id, customer_email
having count(*) > 1
order by count(*) desc
我会说您可以同时使用两者来解决您的问题。
仅订购一次以上的客户:
select customer_email, count(order_id) from Table
group by customer_email having count(order_id)>1
将其与另一个查询产品数量的查询一起添加:
select product_id, count(product_id) from Table
where customer_email in (select customer_email from Table
group by customer_email having count(order_id)>1)
group by product_id having count(product_id)>1
这应该可以解决您的问题。
您可以使用以下方法多次订购产品:
select product_id, count(*) as num_orders, count(distinct customer_email) as num_customers
from t
group by product_id
having count(*) > count(distinct customer_email);
如果订单多于订购的客户,则某些客户订购了不止一次。
您还可以使用:
select distinct product_id
from t
group by product_id, customer_email
having count(*) > 1;
例如,如果您要查看订购超过2次的产品,这将提供更大的灵活性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.