【问题标题】:Average sales in the Nth month of the customer journey客户旅程第 N 个月的平均销售额
【发布时间】:2020-10-05 12:33:05
【问题描述】:

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

【问题讨论】:

  • 到目前为止你尝试过什么?请edit 您的问题包括您当前实施的minimal reproducible example,包括您面临的任何具体错误或问题,以及您为自己解决问题所做的任何尝试。这有助于社区为您提供更有用和相关的答案。

标签: mysql sql python-3.x


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 2021-10-12
    相关资源
    最近更新 更多