对于一个参考月份,我们失去了多少客户,在参考月份有多少客户返回?
Posted
技术标签:
【中文标题】对于一个参考月份,我们失去了多少客户,在参考月份有多少客户返回?【英文标题】:For a reference month, how many customers did we lose and how many customers returned in reference month? 【发布时间】:2019-10-17 09:06:26 【问题描述】:我的最终要求是 - 我需要绘制月度折线图,显示在参考月份重新激活的流失客户的百分比。
因此,对于每个参考月份(例如:2019 年 3 月),我需要查看在 3 月之前我失去了多少客户(2019 年 3 月之前的最后一个“销售日期”比 2019 年 3 月早 3 个月,对于例如:2018 年 11 月、2018 年 10 月、2018 年 9 月、2018 年 8 月、2018 年 7 月......)以及有多少 这些 客户在 2019 年 3 月重新激活(有“销售日期”2019 年 3 月)
你能帮忙写代码吗?我是高级 SQL 的新手,在这一点上卡了很长时间。
Sample Expected Result :
Sale_Month Lost_customers Reactivated_customers
(prev Sale date before (Prev Sale date before
Sale_month > 3 months) Sale_month > 3 months and
have a Sale date in given
Sale month)
Mar-19 1,050 180
Apr-19 900 80
May-19 1,400 160
June-19 1,200 110
July-19 1,800 130
Aug-19 1,900 140
Sample Data :
Customer Sale Date
AAAAA 11/17/2018
BBBBB 11/19/2018
CCCCC 9/22/2018
CCCCC 1/24/2019
AAAAA 3/16/2019 ----> so for Reference month of March, AAAAA to
CCCCC 3/18/2019 be considered in "Lost_customers" because
AAAAA's previous sale date (11/15/2018) is
more than 3 months from the Ref month
(March - 2019) and AAAAA to be considered in
"Reactivated_customers" because AAAAA has a
Sale date in the given month (March-2019)
----> for given month of March, CCCCC to not
be considered in "Lost customers" and
"Reactivated customers" because
previous sale date (1/25/2019) is less
than 3 months from Ref month (March-2019)
and hence does not appear in
"Reactivated_customers" as well
【问题讨论】:
使用Coman table expresion
你可以做到这一点。
@jishansiddique,你能帮我写代码吗?提前致谢!
您能分享您的架构以便更好地理解吗?
@jishansiddique 我的表是一个销售事实表,其信息类似于我的示例数据,但有额外的“销售价格”列。所以基本上,客户 ID、销售日期和销售价格是列
【参考方案1】:
这很复杂。挑战是在没有数据的月份计算客户。一种想法是用每个客户和每个月一行来扩展数据。然后聚合并使用条件聚合:
select yyyymm.yyyymm,
sum( (t.last_yyyymm < yyyymm.last_yyyymm - interval '3 month')::int ) as last_customers,
sum( ((t.last_yyyymm < yyyymm.last_yyyymm - interval '3 month')::int ) and t.yyyymm is not null)::int ) as restarts
from (select distinct customer from t
) c cross join
(select distinct date_trunc('month', saledate) as yyyymm
) yyyymm left join
(select customer, date_trunc('month', saledate) as yyyymm,
min(date_trunc('month', saledate)) over (partition by customer) as min_yyyymm,
lag(date_trunc('month', saledate)) over (partition by customer order by min(saledate)) as last_yyyymm
from t
group by customer, date_trunc('month', saledate)
) t
on t.customer = c.customer and t.yyyymm = yyyymm.yyyymm
group by yyyymm.yyyymm;
【讨论】:
嗨,戈登,非常感谢您提供这段代码,我正在分段运行它,这似乎有效。但是,我想了解,在 y.last_yyyymm 中,表别名 y 来自哪里?请指导。再次感谢! 嗨,戈登,感谢您更新代码。我在最外面的 select 语句中的 yyyymm.last_yyyymm 处收到错误,应该改为 d.yyyymm 吗?请指导。再次感谢您!以上是关于对于一个参考月份,我们失去了多少客户,在参考月份有多少客户返回?的主要内容,如果未能解决你的问题,请参考以下文章