首页 > 解决方案 > 根据原始数据构建时间窗口计数器 - Big Query

问题描述

根据下表考虑有关 2020 年采购的原始事件数据:

BUYER       DATE          ITEM 
Joe     '2020-01-15'      Dr. Pepper
Joe     '2020-02-15'      Dr. Pepper
Joe     '2020-03-15'      Dr. Pepper
Joe     '2020-05-15'      Dr. Pepper
Joe     '2020-10-15'      Dr. Pepper
Joe     '2020-12-15'      Dr. Pepper

我想汇总数据以查看 Joe 在每月移动总和中所做的事情,即作为结果获得

BUYER  Date         Num_Purchases_last_3months
Joe   '2020-01-31'       1
Joe   '2020-02-31'       2
Joe   '2020-03-31'       3
Joe   '2020-04-31'       2
.
.
.
Joe   '2020-11-31'       1
Joe   '2020-12-31'       2

如何在有效的查询中获得所需的结果?

标签: sqlgoogle-bigquery

解决方案


在这种情况下,您可以将窗口函数count(*)range窗口框架规范一起使用:

select t.*,
       count(*) over (partition by buyer
                      order by extract(year from date) * 12 + extract(month from date)
                      range between 2 preceding and current row
                     ) as Num_Purchases_last_3months
from t;

推荐阅读