mysql - 客户旅程第 N 个月的平均销售额
问题描述
我需要按客户的月份查找平均销售额。例如,一位客户在 2020 年 1 月购买了一些产品......然后在 2 月......所以 1 月成为客户的第 1 个月和 2 月 2 日。同样,其他客户在 20 年 4 月第一次购买,下一次在 20 年 6 月购买......所以第 1 个月(4 月)和第 2 个月的平均销售额(4 月和 6 月的平均)预期结果:CustID Month Avg_sales
解决方案
您可以使用窗口函数来获取第一个日期。然后算术。这是一种方法:
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
推荐阅读
- amazon-web-services - 如何将 AWS Kinesis Video Stream(帧)发送到 EC2 实例?
- c# - 如何修改此查询以省略空格或空值?
- r - R中的pivot_wider错误加倍:“数据”中的值不是唯一标识的;输出将包含 list-cols
- sql - SQL where 语句数千个值
- bash - Bash 忽略命令行参数中的引号
- google-apps-script - 谷歌应用脚本从工作表更新表单
- flutter - Flutter-我如何从登录屏幕切换到主页和返回?后端工作但不手动刷新无法显示屏幕
- jenkins - Jenkins 流水线脚本中的当前工作目录
- awk - 从列表中的字符串中提取所有数字
- react-admin - 通过 dataprovider 加载数据后的 react-admin 原始状态