hive练习题(四)

求用户最先购买的两种子类别产品信息(cpzl_zw),要求拼接成 “用户号-产品1-产品2” 的形式

数据表ods_sales_orders的前十行
在这里插入图片描述

第一步:求出每位客户消费的下一个产品

SELECT 
    customer_key, 
    cpzl_zw, 
    row_number() over(partition by customer_key order by create_date) as order_num,
    lag(cpzl_zw,1) over(partition by customer_key order by create_date) as cpzl_zw1
    from ods_sales_orders;

第二步:选出相邻两个产品不一致的记录

create table temp1 as 
SELECT 
    customer_key, 
    cpzl_zw,
    order_num,
    cpzl_zw1 
    from (
    SELECT 
    customer_key, 
    cpzl_zw, 
    row_number() over(partition by customer_key order by create_date) as order_num,
    lag(cpzl_zw,1) over(partition by customer_key order by create_date) as cpzl_zw1
    from ods_sales_orders) a
    where cpzl_zw != cpzl_zw1;

第三步:将相邻两个产品不一致的记录的表中的order_num重新排序,以便选出前两个产品

select customer_key, 
      cpzl_zw, 
      order_num, 
      cpzl_zw1, 
    row_number() over(partition by customer_key order by order_num) as new_order_num
    from temp1

第四步:选出前两个产品,并按照要求输出结果

知识点:with as …

with 
temp1 as (
    SELECT 
    customer_key, 
    cpzl_zw,
    order_num,
    cpzl_zw1 
    from (
    SELECT 
    customer_key, 
    cpzl_zw, 
    row_number() over(partition by customer_key order by create_date) as order_num,
    lag(cpzl_zw,1) over(partition by customer_key order by create_date) as cpzl_zw1
    from ods_sales_orders) a
    where cpzl_zw != cpzl_zw1),
temp2 as (
    select customer_key, 
      cpzl_zw, 
      order_num, 
      cpzl_zw1, 
    row_number() over(partition by customer_key order by order_num) as new_order_num
    from temp1)
select 
concat(customer_key,'_',concat_ws('_',collect_set(cpzl_zw))) as z1
from temp2
where new_order_num <3
group by customer_key;

结果局部截图:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值