购买日期 | 客户编号 | 销售单位 |
---|---|---|
2018-01-01 | 1 | 10 |
2018-01-02 | 1 | 5 |
2018-01-05 | 2 | 3 |
2018-01-15 | 1 | 10 |
2018-01-20 | 2 | 4 |
购买日期 | 客户编号 | 销售单位 | 每7天累计销售额 |
---|---|---|---|
2018-01-01 | 1 | 10 | 10 |
2018-01-02 | 1 | 5 | 15 |
2018-01-15 | 1 | 10 | 10 |
2018-01-05 | 2 | 3 | 3 |
2018-01-20 | 2 | 4 | 4 |
从上面的表格,我现在有第一张表格,并试图从这个客户购买的第一天开始每 7 天的销售额。 (我先插入表格,但不知道如何在表格上方添加文字)
困难的部分是:
每个顾客的第一天购买都不一样
购买日期不是后继的,所以我不能使用unbonded或following 6 rows等
整个数据集有5年,所以我不能手动-7、-14等
我尝试使用 date_trunc('week',date, min(date) over (partition by customerid))
还尝试在 6 个处理行和当前行之间按行进行分区。但是日期不是结果所以不起作用
您可以通过2个步骤使用SQL窗口函数来获得您想要的结果:
步骤 1. 按每个客户应用窗口分区并获取每个客户的 first_purchase_date。之后,使用 Presto date_diff() 函数计算从第一次购买日期到当前购买日期的日期差异。将它除以 7 得到从购买的第一个日期算起的 week_bucket。
第 2 步。按每个 (customer, customer_sale_week_bucket) 应用窗口分区,并在每个 (customer, customer_sale_week_bucket) 分区中获取 sum(sales_unit)。
这是 Presto 中的查询:
with orders_with_customer_week_bucket AS
(
select
purchase_date,
customer_id,
sales_unit,
date_diff(day,min(purchase_date) over (partition by customer_id), purchase_date) / 7 as customer_sale_week_bucket
from
orders
)
select
purchase_date,
customer_id,
sales_unit,
sum(sales_unit) over (partition by customer_id, customer_sale_week_bucket) as every_7_day_cumulative_sales
from
orders_with_customer_week_bucket
购买日期 | customer_id | 销售单位 | every_7_day_cumulative_sales |
---|---|---|---|
2018-01-01 | 1 | 10 | 15 |
2018-01-02 | 1 | 5 | 15 |
2018-01-15 | 1 | 10 | 10 |
2018-01-05 | 2 | 3 | 3 |
2018-01-20 | 2 | 4 | 4 |