首页 > 解决方案 > 客户旅程第 N 个月的平均销售额

问题描述

我需要按客户的月份查找平均销售额。例如,一位客户在 2020 年 1 月购买了一些产品......然后在 2 月......所以 1 月成为客户的第 1 个月和 2 月 2 日。同样,其他客户在 20 年 4 月第一次购买,下一次在 20 年 6 月购买......所以第 1 个月(4 月)和第 2 个月的平均销售额(4 月和 6 月的平均)预期结果:CustID Month Avg_sales

标签: mysqlsqlpython-3.x

解决方案


您可以使用窗口函数来获取第一个日期。然后算术。这是一种方法:

select custid, year(date) * 12 + month(date) - (year(first_date) * 12 + month(first_date)) as diff,
       avg(sales) as avg_sales
from (select t.*,
             min(date) over (partition by custid) as first_date
      from t
     ) t
group by custid, diff

推荐阅读