计算客户平均购买一次商品的间隔时间
数据ods_sales_orders字段
第一步:找出用户第一次下单后的下一笔订单的消费日期
知识点:lead函数
将用户的下单日期按照从早到晚排序,可以看到最早消费日期为‘2018-12-31’,考虑到有用户只消费了一次,找不到下次订单的消费日期,所以在lead函数中将找不到的值,默认设为‘2018-12-31’,这样在计算两笔订单消费日期的时间跨度时,可以过滤掉只消费过一次的用户。
SELECT customer_key,create_date,lead(create_date, 1, '2018-12-31')
OVER(PARTITION BY customer_key ORDER BY create_date) AS next_buy_time
FROM ods_sales_orders;
第二步:计算两笔订单消费的间隔日期
SELECT customer_key,create_date,datediff(lead(create_date, 1,'2018-12-31') OVER(PARTITION BY customer_key ORDER BY create_date),create_date) as diff_day
FROM ods_sales_orders;
第三步:计算客户平均购买一次商品的间隔时间
select customer_key,avg(diff_day) as avg_per from
(SELECT customer_key,create_date,datediff(lead(create_date, 1,'2018-12-31') OVER(PARTITION BY customer_key ORDER BY create_date),create_date) as diff_day
FROM ods_sales_orders) a
where diff_day>0 group by customer_key;