hive - 面试题 - 最近一次购物在一年前(近一年内无购物)

要求:
有表:用户id,订单id,下单日期
该用户符合365天内无交易且当日有交易的数据打标签,如果当天有多条记录,同样打标签。

思路:
当前订单时间 - 最近一次的下单时间 >= 365 ,即最近365天内无订单记录。
中间有个问题,一天内多次下单,只能先写子查询去重,后续再关联出全天所有记录,不知道有没有其他合适的方式。

WITH o AS 
(
    SELECT  '01' AS userid
            ,'1001' AS orderid
            ,CAST('2023-01-01' AS DATE) AS paydate
    UNION ALL
    SELECT  '01' AS userid
            ,'1002' AS orderid
            ,CAST('2024-08-02' AS DATE) AS paydate
    UNION ALL
    SELECT  '01' AS userid
            ,'1003' AS orderid
            ,CAST('2024-08-02' AS DATE) AS paydate
    UNION ALL
    SELECT  '02' AS userid
            ,'1000' AS orderid
            ,CAST('2021-01-01' AS DATE) AS paydate
    UNION ALL
    SELECT  '02' AS userid
            ,'1004' AS orderid
            ,CAST('2023-01-02' AS DATE) AS paydate
    UNION ALL
    SELECT  '02' AS userid
            ,'1005' AS orderid
            ,CAST('2023-08-02' AS DATE) AS paydate
    UNION ALL
    SELECT  '03' AS userid
            ,'1006' AS orderid
            ,CAST('2023-01-01' AS DATE) AS paydate
)
SELECT  o.*
        ,d.flag
FROM    o AS o
LEFT JOIN   (
                SELECT  userid
                        ,paydate
                        ,f_date
                        ,CASE   WHEN DATEDIFF(paydate,f_date) >= 365 THEN 'yes'
                                ELSE 'no'
                        END AS flag
                FROM    (
                            SELECT  userid
                                    ,paydate
                                    ,LAG(paydate,1,'') OVER (PARTITION BY userid ORDER BY paydate ASC ) AS f_date
                            FROM    (
                                        SELECT  userid
                                                ,paydate
                                        FROM    o
                                        GROUP BY userid
                                                 ,paydate
                                    ) AS c
                        ) AS a
            ) AS d
ON      o.userid = d.userid
AND     o.paydate = d.paydate
;




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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值