【问题标题】:How can I extract customers who have transacted since a specific date? (active customers definition)如何提取自特定日期以来进行过交易的客户? (活跃客户定义)
【发布时间】:2021-04-26 10:29:47
【问题描述】:

全部,

我对活跃客户的定义是自 2019 年 11 月以来进行过交易的任何人。我不确定如何做到这一点。例如

select 
customerid, 
sum(count) as transaction_count,
sum(value) as dollar_amount

from 
cust_orders 

我上面的表处于事务级别,例如transaction_id = 1, 2... etc..我在客户级别汇总它,但我只想要自 2019 年 11 月以来至少交易过一次的客户。我认为这不像添加这样简单:'where yearmonth > 201911 '。因为例如如果我有一位客户从那以后没有进行过交易,我不想要他们上面的任何汇总统计信息。如果我有自 2019 年 11 月以来进行交易的客户,我确实希望他们在此之前的交易计数包括在内。也许我可以这样做:

select 
customerid, 
sum(count) as transaction_count,
sum(value) as dollar_amount

from 
cust_orders where customerid in (select 

distinct

customerid 

from cust_orders where yearmonth > 201911))
)

这有意义吗?

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    首先,您需要在第一个查询中进行聚合。其次,您可以使用HAVING 子句来识别活跃客户:

    select customerid, 
           sum(count) as transaction_count,
           sum(value) as dollar_amount
    from cust_orders 
    group by customerid
    having max(yearmonth) >= 201911;
    

    注意:我将“自 2011 年 11 月以来”解释为包括该月,因此我将比较更改为 >=

    【讨论】:

    • 所以在计数中这仍将包括 2011 年 11 月之前的交易,因为它在聚合后过滤? (有子句)
    • @Maths12 。 . .确切地。如果您只想要sum()s 中自该日期以来的值,您将使用where
    • 谢谢,你为什么要做 max(yearmonth) 而不仅仅是 yearmonth >= 201911?
    • @Maths12 。 . .因为它是一个having 子句,任何包含不在group by 中的列的表达式都需要使用聚合函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多