热线电话:13121318867

登录
2023-07-20 阅读量: 432
Cda数据分析——Sql淘宝案例(四)行为转化分析(看人头,不看人次)

每一天的用户行为数,要注意在日期和行为分组后,对用户id进行去重计数。

# 查询每一天的用户行为数
select  日期,
         behavior_type,
      count(distinct(user_id)) as 用户行为数
from userbehavior_new
group by 日期,behavior_type
order by 日期,behavior_type desc;

查询每种行为的转化率,要注意在为行为分组后,去重计数得到每种行为的用户数量,然后用该数量厨艺通过标量子查询得到的pv(浏览)的用户人数得到每种行为相对于pv的转化率。

# 查询每种行为的转化率
select   behavior_type,
       count(distinct user_id) as 用户数,
      count(distinct user_id) / (select  count(distinct user_id ) 
                                    from userbehavior_new 
                                    where behavior_type = 'pv') as 转化率
from userbehavior_new
group by behavior_type
order by behavior_type desc;

通过上面得到的数据可知收藏行为在该漏斗分析环节没有太多意义,所以只探查浏览 → 加购 → 购买的转化率,查询浏览 → 加购 → 购买的转化率,查询该情况需要在得到每种行为的用户数后,使用开窗函数lag,作用是的得到一个新列,得到每个用户的上一行为用户数,该需求需要达成正确的排列顺序及:pv,cart,buy后才能对之后求转化率起到作用,而Order by 是最后才执行的操作,所以在lag开窗函数中要进行排序,最后可以用ifnull完善

# 查询浏览 → 加购 → 购买的转化率
select  behavior_type,
        count(distinct user_id) as 用户数,
     ifnull(lag(count(distinct user_id),1)over(order by behavior_type desc),count(distinct user_id)) as 上一用户数,
     ifnull(count(distinct user_id)/lag(count(distinct user_id),1)over(order by behavior_type desc),1) as 转化率
from userbehavior_new
where behavior_type not like 'fav'
group by behavior_type;

在查询每天浏览 → 加购,加购 → 购买的转化率这一指标中,有两种方法供大家参考,其一,是类似于上一种,使用开窗函数和子查询中间表的方式,得到转化率需要一个中间表,需要注意的是,增加日期分组后,得到每天的行为转化率,将其作为中间表,利用sum(if())聚合得到每天的相关转化率

# 查询每天浏览 → 加购,加购 → 购买的转化率
select 日期,
        sum(if(behavior_type='cart',转化率,0)) as '浏览 → 加购转化率',
     sum(if(behavior_type='buy',转化率,0)) as '加购 → 购买转化率'
from(   select 日期,
             behavior_type,
             count(distinct user_id) as 用户数,
             lag(count(distinct user_id),1)over(partition by 日期 order by behavior_type desc) as 每天上一用户数,
             count(distinct user_id)/lag(count(distinct user_id),1)over(partition by 日期 order by behavior_type desc) as 转化率
        from userbehavior_new
        where behavior_type not like 'fav'
        group by 日期,behavior_type
    ) as T
group by 日期;

其二,是不使用开窗函数,使用两个子查询获得,首先得到每天每种行为的用户数,再将其作为中间表,通过聚合函数将纵向数据变为横向,再将此作为子表,通过除法得到转化率。

select  日期,
         cart/pv as '浏览 → 加购转化率',
         buy/cart as '加购 → 购买转化率'
from(  select 日期,
             sum(if(behavior_type='pv',用户数,0)) as pv,
             sum(if(behavior_type='cart',用户数,0)) as cart,
             sum(if(behavior_type='buy',用户数,0)) as buy
        from(  select 日期,
                    behavior_type,
                    count(distinct user_id) as 用户数
   
               from userbehavior_new
               where behavior_type not like 'fav'
               group by 日期,behavior_type
            )    as T1
        group by 日期
    ) as T2;




0.0000
0
关注作者
收藏
评论(0)

发表评论

暂无数据