2016-03-25 37 views
1

我對一種邏輯可能無法接受感到抱怨。重複客戶在MySQL中明智月月

但我的要求是我想要的客戶數(NewCustomers,repeatCustomers)以前和當前月份的基礎上,從這個數據

就像我想

DATE  NAME 
2016-01-01 A 
2016-01-01 B 
2016-01-01 C 
2016-01-05 E 
2016-01-05 F 
2016-01-25 G 
2016-01-25 H 
2016-02-25 A 
2016-02-25 E 
2016-02-10 X 
2016-02-11 Y 
2016-02-13 F 

輸出這樣

MONTH NewCustomer  RepeatCustomer CustomerCount of refernece month (Like here is JAN) 


FEB  2    3    7 

未來幾個月也會如此

任何建議n?謝謝 !!

回答

0

我不知道參考月份是什麼,但你可以通過組合第一一次你看到誰在每個月拜訪一個客戶得到前兩列:

select date_format(c.date, '%Y-%m') as yyyymm, 
     count(distinct c.name) as NumCustomers, 
     sum(case when date_format(c.date, '%Y-%m') <> date_format(cc.start_date, '%Y-%m') 
       then 1 else 0 
      end) as NumRepeatCustomers 
from customers c join 
    (select c.name, min(c.date) as start_date 
     from customers c 
     group by c.name 
    ) cc 
    on c.name = cc.name 
group by date_format(c.date, '%Y-%m') 
order by yyyymm; 
+0

像那一年所以在1月份就不會有回頭客了,所有的都會是新的,如果1月份的客戶也是如此,FEB可能會是。所以在這種情況下,jan是我尋找回頭客的Ref月份。 – Kate