運營需求拆解:
單一復購率公式(按周計算,需要計算從4.1-8.4的數據):
分子:本周和上周對同一商戶都下過單的人數
分母:上周下過訂單的總人數
注:需要考慮到可疑訂單,即刷單的狀況
需求拆解:難點在與分子計算;
需求進一步拆解:本周和上周對同同一商戶下過單,則可以理解為用戶的復購;
可以把用戶和商戶 看成是一組,計算他們的復購即可;
具體代碼如下:
with tmp_weekly_user_god as (
select
concat(to_char(DATEADD(trade_date,-WEEKDAY(trade_date),'dd'),'yyyymmdd')
,'~' ,to_char(DATEADD(trade_date,6-WEEKDAY(trade_date),'dd'),'yyyymmdd')) as weekly_range
,weekofyear(trade_date) as weekly
,weekofyear(trade_date)+ 1 as next_weekly
,from_user_id
,to_user_id
,concat('-',from_user_id,to_user_id) as group_group -- 組合
from ypp_trade_flow
where trade_type = 'ORDER' -- 交易訂單
And TO_CHAR(trade_date,'yyyymmdd') between '20190401' and '20190804'
group by concat(to_char(DATEADD(trade_date,-WEEKDAY(trade_date),'dd'),'yyyymmdd')
,'~' ,to_char(DATEADD(trade_date,6-WEEKDAY(trade_date),'dd'),'yyyymmdd'))
,from_user_id
,to_user_id
,weekofyear(trade_date)
)
-- 留存率計算
select
t1.weekly `周`
,t1.weekly_range `周維度`
,'全部' as `類型`
,count(distinct t1.from_user_id) as `純用戶下單人數`
,count(distinct t1.group_group) as `一組下單人數`
,count(distinct t2.group_group) as `一組本周用戶大神在上周繼續下單人數`
--,concat('',round(count(distinct t1.group_group)/count(distinct t2.group_group),4)*100,'%') as `單一復購率公式`
from tmp_weekly_user_god t1
left join tmp_weekly_user_god t2
on t1.group_group = t2.group_group
and t1.weekly = t2.next_weekly
group by t1.weekly,t1.weekly_range
結果集如下:


細節問題:
- 周維度:如果只使用weekofyear 只是給了一個具體的數字,而不清楚具體的周開始時間和結束時間,因此可以加上,更直觀,起代碼如下:
concat(to_char(DATEADD(trade_date,-WEEKDAY(trade_date),'dd'),'yyyymmdd'),'~' ,to_char(DATEADD(trade_date,6-WEEKDAY(trade_date),'dd'),'yyyymmdd'))
拆分下:
周開始時間:```to_char(DATEADD(trade_date,-WEEKDAY(trade_date),'dd'),'yyyymmdd')``
周結束時間:to_char(DATEADD(trade_date,6-WEEKDAY(trade_date),'dd'),'yyyymmdd')
- 運營的需求,細節還是有一點點問題,有沒有發現,這個后續和運營溝通解決了;
參考:
[Get the week start date and week end date from week number in SQL Server - Stack Overflow](
