【问题标题】:Weekly active or lapsing status in BigQueryBigQuery 中的每周活动或失效状态
【发布时间】:2022-07-11 11:31:53
【问题描述】:

我想根据客户的活动每周查看他们的状态。

如果客户在过去 7 天内进行过交易,则应显示为活跃,如果客户在 8-21 天内未进行过交易,则应显示为“失效”。 我的表中有这些值: enter image description here

所需的输出参考: 周# Customer_id 状态

【问题讨论】:

  • 您想要每个星期和 customer_id 组合的行吗?

标签: sql google-bigquery tagging


【解决方案1】:

如果您希望每个 week 和 customer_id 组合都有一行,您可以从您的订单表中创建这两者的不同组合的大型交叉连接,然后将所有订单匹配回该超集,保持最新(在那之前日期)。

with base_table as (
  select distinct customer_id, week_date
  from orders
  cross join (SELECT week_date FROM UNNEST(GENERATE_DATE_ARRAY((select min(order_date) from orders), CURRENT_DATE(), INTERVAL 7 DAY)) AS week_date)
)
select base_table.customer_id, base_table.week_date, max(order_date) as latest_order, 
case 
  when DATE_DIFF(week_date,max(order_date),DAY) <= 7 then 'active'
  when DATE_DIFF(week_date,max(order_date),DAY) >= 8 and DATE_DIFF(week_date,max(order_date),DAY) <= 21 then 'lapsing'
  else 'not active'
end as status
from base_table
cross join orders
where orders.customer_id = base_table.customer_id
and order_date <= week_date
group by 1, 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    • 2020-11-03
    相关资源
    最近更新 更多