考虑有关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如何在高效的查询中获得所需的结果?
发布于 2020-09-22 02:38:46
您可以使用窗口函数,在本例中,使用带有range窗口框架规范的count(*):
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;https://stackoverflow.com/questions/63998124
复制相似问题