2016-03-25 32 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