sql - 根据原始数据构建时间窗口计数器 - 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
如何在有效的查询中获得所需的结果?
解决方案
在这种情况下,您可以将窗口函数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;
推荐阅读
- javascript - Nodejs .Unable to send oauth v1 params in get request with axios
- php - 您的要求无法解决为一组可安装的软件包。- Laravel 流明邮件
- linux - linux - df 命令说磁盘 100% 已使用,但实际上并非如此
- asp.net-mvc-4 - 需要一种在网页中嵌入 rdlc 设计器的方法
- java - 单击毕加索时如何显示图像
- crystal-reports - 如何将一些十进制数字删除到业务伙伴帐龄(摘要报告)字段?
- php - 如何使用确切数量的参数查找函数调用
- c++ - 什么会在这个程序中产生内存泄漏
- xamarin.forms - 将 AutoMapper 从 7.0.0 升级到 9.0.0 后面临映射异常
- api - Microsoft Graph 活动 - 401 AAD 身份验证失败