有一张运单表:dwd_biz_waybill_td,该表的主键是way_bill_id,并且有如下字段:
way_bill_id(运单表主键),shiping_date(下单日期,时间格式为yyyy-MM-dd),payment_customer_id(付款客户),damaged_degree_type(是否严重破损,为枚举值。1为是,0为否),is_throw_away(是否丢失,为枚举值。1为是,0为否),is_pickup_overtime(是否取超时,为枚举值。1为是,0为否)。需求为:
求连续俩周 严重破损的客户,丢失的客户、取超时的客户。
思路:
步骤一:
求每天严重破损、取超时的客户
with v_customer_votes_base_data as (
select
waybill_td.payment_customer_id,
waybill_td.shiping_date,
CASE
when shiping_date>= date_format(date_trunc('week',current_date),'%Y-%m-%d') then 'cur_week'
when cast(date_add('day',-7,cast(date_format(date_trunc('week',current_date),'%Y-%m-%d') as date )) as varchar)<=shiping_date
and shiping_date= cast(date_add('day',-7,cast(date_format(date_trunc('week',current_date),'%Y-%m-%d') as date )) as varchar)
and waybill_td.shiping_date<= date_format(current_date,'%Y-%m-%d')
group by waybill_td.payment_customer_id,waybill_td.shiping_date
),
第二步,求本周与上周的相关指标
/*客户连续俩周的相关指标*/
v_customer_votes_result as (
select payment_customer_id,
shiping_date_week, /*本周还是上周*/
sum(payment_serious_damage_votes) as payment_serious_damage_votes , /*严重破损*/
sum(payment_throw_away_votes) as payment_throw_away_votes, /*丢失票(排除退栏单)*/
sum(payment_order_pickup_overdue_votes) as payment_order_pickup_overdue_votes, /*订单取超时数*/
sum(payment_inner_overdue_votes) as payment_inner_overdue_votes /*内因超时票(内因)*/
from v_customer_votes_base_data
where shiping_date_week is not null
group by payment_customer_id,shiping_date_week
)
第三部,将本周与上周的指标打平成一行
/*客户连续俩周的相关指标*/
v_customer_votes_result_two_week as (
select payment_customer_id,
sum(if(shiping_date_week='cur_week' and payment_serious_damage_votes>0,
1,
0)
) as payment_serious_damage_votes,
sum(if(shiping_date_week='last_week' and payment_serious_damage_votes>0,
1,
0)
) as payment_serious_damage_votes_last_week,
sum(if(shiping_date_week='cur_week' and payment_throw_away_votes>0,
1,
0)
) as payment_throw_away_votes,
sum(if(shiping_date_week='last_week' and payment_throw_away_votes>0,
1,
0)
) as payment_throw_away_votes_last_week,
sum(if(shiping_date_week='cur_week' and payment_order_pickup_overdue_votes>0,
1,
0)
) as payment_order_pickup_overdue_votes,
sum(if(shiping_date_week='last_week' and payment_order_pickup_overdue_votes>0,
1,
0)
) as payment_order_pickup_overdue_votes_last_week
from v_customer_votes_result
group by payment_customer_id
)
第四步:计算结果:
select
if(payment_serious_damage_votes>0 and payment_serious_damage_votes_last_week>0,1,0) as is_serious_damage_tw, /*是否【连续2周】严重破损*/
if(payment_throw_away_votes>0 and payment_throw_away_votes_last_week>0,1,0) as is_serious_damage_tw /*是否【连续2周】丢失*/
if(payment_order_pickup_overdue_votes>0 and payment_order_pickup_overdue_votes_last_week>0,1,0) as is_serious_damage_tw, /*是否【连续2周】取超时*/
from v_customer_votes_result_two_week