【问题标题】:Flaggin active customers - Atleast one transaction every month标记活跃客户 - 每月至少一笔交易
【发布时间】:2019-07-18 13:31:12
【问题描述】:

客户注册后,在 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

【问题讨论】:

    标签: sql hive


    【解决方案1】:

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

    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;
    

    【讨论】:

    • 谢谢戈登。对于任何给定的客户,是否有可能在 min(trn_date) 和 max(trn_date) 之间,如果他/她每个月都活跃,然后标记为“活跃”,否则标记为“不活跃”?
    • 嗨,是否可以在 Prestodb 中编写此查询?考虑到 last_day 和 months_between 函数不可用
    • @NamanDoshi 。 . .如果你有关于 PrestoDB 的问题,那么你应该问一个新的问题。这个问题很明显是关于 Hive 的。
    猜你喜欢
    • 2020-08-30
    • 2022-11-02
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2022-01-06
    相关资源
    最近更新 更多