计算新用户订阅量MySQL

时间:2018-02-22 14:51:55

标签: mysql sql partition

我有一个数据集,我需要找到新订阅者的收入。

这些订阅者每周或每月付费,具体取决于他们所订阅的订阅。

唯一标识符是“customer”,数据处于时间戳级别,但我希望它以月度级别汇总。

现在每个月,我们都需要为新订阅者找到收入。 基本上,想象一下客户每月/每周订阅,我们只想在这里计算他们的第一笔付款。

这是一个示例数据集和

created            customer                  amount
16-Feb-18 14:03:55  cus_BwcisIF1YR1UlD  33300
16-Feb-18 14:28:13  cus_BpLsCvjuubYZAe  156250
15-Feb-18 19:19:14  cus_C3vT6uVBqJC1wz  50000
14-Feb-18 23:00:24  cus_BME5vNeXAeZSN2  162375
9-Feb-18 14:27:26   cus_BpLsCvjuubYZAe  156250

....等等......

这是最终的期望输出

yearmonth new_amount
Jan - 2018   100000
Feb - 2018   2000
Dec - 2017   100002

这需要在MySQL界面中完成。

2 个答案:

答案 0 :(得分:1)

基本上,您希望将数据过滤到第一个客户。执行此操作的一种方法涉及相关子查询。

其余的只是按年和月汇总。因此,总体而言,查询并不复杂,但它确实包含两个不同的部分:

select year(created) as yyyy, month(created) as mm,
       count(*) as num_news,
       sum(amount) as amount_news
from t
where t.created = (select min(t2.created)
                   from t t2
                   where t2.customer = t.customer
                  )
group by yyyy, mm

答案 1 :(得分:1)

   We can have sql subquery for only the 1st payment of the new customer with   
   amount for every month and year

   The query is as follows

  SELECT month(created) as mm,year(created) as yyyy,
  sum(amount) as new_amount
  FROM t
  WHERE t.created=(select min(t2.created) from t t2 where 
    t2.customer=t.customer)