簡體   English   中英

查找客戶多次訂購的產品

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM