使用sql查找重复率

时间:2017-07-09 08:55:41

标签: sql

我有一张下面提到的表格: 如果X客户在1月份进行了购买,那么他们中有多少人在2月就开始购买,即Y.(重复率:Y / X * 100)

customer_no month
---------------------
1           jan
2           jan
3           jan
4           jan
11          jan
1           feb
2           feb
3           feb
9           feb
10          feb

输出:

 Repeat_Rate
 60%

1 个答案:

答案 0 :(得分:1)

我会这样做:

   SELECT CAST(COUNT(yourtable_feb.customer_no) as FLOAT) 
          / CAST(COUNT(yourtable_jan.customer_no) AS FLOAT) AS Repeating_Rate
     FROM yourtable yourtable_jan
LEFT JOIN yourtable yourtable_feb
       ON yourtable_jan.customer_no = yourtable_feb.customer_no 
      AND yourtable_feb.mymonth = 'feb'
    WHERE yourtable_jan.mymonth = 'jan'

这里有一个rextester,如果你想重新测试我的查询: http://rextester.com/ESO11614