活跃客户-每月至少完成一笔交易

时间:2019-07-18 13:31:12

标签: sql hive

客户注册后,在date_registered和当前日期之间-如果客户每月至少进行一笔交易,则将其标记为有效,否则将其标记为无效

注意:每个客户都有不同的date_registered

我尝试过此操作,但由于在今年中期很少有客户加入,因此无法正常工作 例如-

-------------------------------------
txn_id | txn_date | name | amount
-------------------------------------
101     2018-05-01  ABC    100
102     2018-05-02  ABC    200
-------------------------------------
       (case when count(distinct case when txn_date >= '2018-05-01' and txn_date < '2019-06-01' then last_day(txn_date) end) = 13
             then 'active' else 'inactive'
        end) as flag
from t;

最终输出

----------------
name | flag
----------------
ABC    active
BCF    inactive

1 个答案:

答案 0 :(得分:0)

您可以对聚合查询使用过滤:

select customer,
       count(distinct last_day(txn_date)) as num_months
from (select t.*, min(date_registered) over (partition by customer) as min_dr
      from t
     ) t
group by customer, min_dr
having count(distinct last_day(txn_date)) = months_between(last_day(current_date), last_day(min_dr)) + 1;

注意:如果客户在一个月的第一天都没有交易,那么到一个月初可能会产生意外的结果。

编辑:

如果要标记,只需将HAVING逻辑移至SELECT

select customer,
       (case when count(distinct last_day(txn_date)) = months_between(last_day(current_date), last_day(min_dr)) + 1
             then 'Active' else 'Inactive'
        end) as active_flag
from (select t.*, min(date_registered) over (partition by customer) as min_dr
      from t
     ) t
group by customer, min_dr;