I have the following table showing when customers bought a certain product. The data I have is CustomerID, Amount, Dat. I am trying to create the column ProductsIn30Days, which represents how many products a customer bought in the range Dat-30 days inclusive the current day.
For example, ProductsIn30Days for CustomerID 1 on Dat 25.3.2020 is 7, since the customer bought 2 products on 25.3.2020 and 5 more products on 24.3.2020, which falls within 30 days before 25.3.2020.
| CustomerID | Amount | Dat | ProductsIn30Days |
|---|---|---|---|
| 1 | 1 | 23.3.2018 | 1 |
| 1 | 2 | 24.3.2020 | 2 |
| 1 | 3 | 24.3.2020 | 5 |
| 1 | 2 | 25.3.2020 | 7 |
| 1 | 2 | 24.5.2020 | 2 |
| 1 | 1 | 15.6.2020 | 3 |
| 2 | 7 | 24.3.2017 | 7 |
| 2 | 2 | 24.3.2020 | 2 |
I tried something like this with no success, since the partition only works on a single date rather than on a range like I would need:
select CustomerID, Amount, Dat,
sum(Amount) over (partition by CustomerID, Dat-30)
from table
Thank you for help.