【发布时间】:2021-09-01 09:13:24
【问题描述】:
我在 bigquery 中有一个数据集,其中包含 order_date: DATE 和 customer_id。
order_date | CustomerID
2019-01-01 | 111
2019-02-01 | 112
2020-01-01 | 111
2020-02-01 | 113
2021-01-01 | 115
2021-02-01 | 119
我尝试在上一年的月份和当年的相同月份之间计算不同的 customer_id。比如从2019-01-01到2020-01-01,然后从2019-02-01到2020-02-01,然后谁没有在明年同期2020-01-01到2021- 01-01,然后 2020-02-01 到 2021-02-01。
我期望的输出
order_date| count distinct CustomerID|who not buy in the next period
2020-01-01| 5191 |250
2020-02-01| 4859 |500
2020-03-01| 3567 |349
..........| .... |......
并且下一个期间不应包括上一个。
我尝试了下面的代码,但它以另一种方式工作
with customers as (
select distinct date_trunc(date(order_date),month) as dates,
CUSTOMER_WID
from t
where date(order_date) between '2018-01-01' and current_date()-1
)
select
dates,
customers_previous,
customers_next_period
from
(
select dates,
count(CUSTOMER_WID) as customers_previous,
count(case when customer_wid_next is null then 1 end) as customers_next_period,
from (
select prev.dates,
prev.CUSTOMER_WID,
next.dates as next_dates,
next.CUSTOMER_WID as customer_wid_next
from customers as prev
left join customers
as next on next.dates=date_add(prev.dates,interval 1 year)
and prev.CUSTOMER_WID=next.CUSTOMER_WID
) as t2
group by dates
)
order by 1,2
提前致谢。
【问题讨论】:
-
是否有任何我们可以看到的代码代表您尝试过的代码,或者您正在寻求帮助而没有花任何时间解决问题?
标签: sql google-bigquery