销售订单首购和次购分析
题目需求
通过商品信息表(sku_info)订单信息表(order_info)订单明细表(order_detail)分析如果有一个用户成功下单两个及两个以上的购买成功的手机订单(购买商品为xiaomi 10,apple 12,小米13)那么输出这个用户的id及第一次成功购买手机的日期和第二次成功购买手机的日期,以及购买手机成功的次数。
结果如下:
| User_id
(用户id) | First_date
(首次时间) | Last_value
(末次时间) | Cn
(购买次数) |
| — | — | — | — |
| 101 | 2021-09-27 | 2021-09-28 | 3 |
| 1010 | 2021-10-08 | 2021-10-08 | 2 |
| 102 | 2021-10-01 | 2021-10-01 | 3 |
| 103 | 2021-09-30 | 2021-10-02 | 2 |
| 104 | 2021-10-03 | 2021-10-03 | 3 |
| 105 | 2021-10-04 | 2021-10-04 | 2 |
| 106 | 2021-10-04 | 2021-10-05 | 3 |
| 107 | 2021-10-05 | 2021-10-05 | 3 |
| 108 | 2021-10-06 | 2021-10-06 | 3 |
| 109 | 2021-10-07 | 2021-10-07 | 3 |
代码实现
select
distinct oi.user_id,
first_value(od.create_date)over(partition by oi.user_id order by od.create_date rows between unbounded preceding and unbounded following ) first_date,
last_value(od.create_date)over(partition by oi.user_id order by od.create_date rows between unbounded preceding and unbounded following ) last_date,
count(*)over(partition by oi.user_id order by od.create_date rows between unbounded preceding and unbounded following) cn
from
order_info oi
join
order_detail od
on
oi.order_id=od.order_id
join
sku_info si
on
od.sku_id=si.sku_id
where
si.name in('xiaomi 10','apple 12','xiaomi 13')