Customer/Material对统计过去3年出现的次数并设置状态标志。 -aws 红移

Customer/Material pair to count the occurences in the past 3 years and set the status flag. - aws redshift

我有一个 table 具有以下值

日期 客户姓名 material
9/1/2020 一个 A1
2019 年 8 月 1 日 一个 A2
2018 年 8 月 1 日 一个 A2
9/2/2020 B A1
9/2/2019 B A2
9/2/2017 B A2

所以输出应该是这样的,如果我能看到一个客户 material,他在过去 3 年里有过一次入驻,那么状态标志应该是 Yes,否则状态标志应该没有。

日期 客户姓名 material 状态
9/1/2020 一个 A1 没有
2019 年 8 月 1 日 一个 A2
2018 年 8 月 1 日 一个 A2 没有
9/2/2020 B A1 没有
9/2/2019 B A2
9/2/2017 B A2 没有

我正在考虑计算 customer/material 对在过去 3 年中出现的给定次数,并检查计数以设置状态标志。但是对如何使用窗口函数感到困惑?

select customer_name, material, count(*) from table 
where datediff(year, date, current_date) <=3
group by customer_name, material

然后加入这个table,但我觉得这种方法是错误的,因为它没有考虑滚动状态。

谢谢!

使用window 函数。可能最简单的是 lag():

select t.*,
       (case when lag(date) over (partition by customer, material order by date) >= date - interval '3 year'
             then 'Yes' else 'No'
        end) as flag
from t