简体   繁体   中英

Find products which customers ordered multiple times

There is a mysql table where an online shop's order items are stored. The most important fields of the table:

  • order_item_id
  • product_id
  • order_id
  • customer_email (from a joined table)

I want to find which products are what the same customers are ordering again and again. Basically we need only customers who have ordered more than once. For these users I want to check if there are products which they ordered more than once. Eg usually you order a laser printer only once but you order toners later. I need the information when a customer ordered a toner at least twice to check which are the products which the customers need more than once or they are so satisfied with the product, that they order a second one. Do I need some GROUP BY or subquery for that?

You could try using a group by and having count > 1

select product_id, customer_email , count(*)
from  my_table  
group by product_id, customer_email 
having count(*) > 1 
order by count(*) desc  

I would say you can use both to solve your problem.

Customers who only ordered more than once:

select customer_email, count(order_id) from Table
group by customer_email having count(order_id)>1

Add it with another query counting number of products:

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

This should solve your problem.

Your can get the products ordered more than once using:

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);

If there are more orders than customers who ordered, then some customer ordered more than once.

You could also use:

select distinct product_id
from t
group by product_id, customer_email
having count(*) > 1;

This gives more flexibility if you want to see products ordered more than 2 times, for instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM