Hi all,
I need some help. I've been spending the last few hours trying to resolve an issue I'm having when using the OVER function in SQL.
I'm trying to create a rolling moving average (in my case 30 days) however I don't want SQL to look back and calculate it based on the 30 previous rows. In my case, I wish it does it based on my date field.
For example, as per the table below, I wish to know the maximum size on each date when compared to the previous 30 days. In my first entry (7/17/2013), the answer would be 2161. In the second (7/24/2013) entry it would be 2161 again. In my third (11/27/2013), fourth (12/04/2013) and fifth (12/12/2013) entry the answer would be 1414. Basicaly, I need SQL to go back in time on every date, look over the previous 30 days and determine the MAX value each time.
The Query I use the following:
SELECT Date, Product, MAX([uANCT.P30D]) OVER (PARTITION BY Product ORDER BY Date, Product ROWS 30 PRECEDING
However, it looks for rows (30 preceding) and I need it to work for the 30 PRECEDING days
Can someone please help me. It's really appreciated!
Cheers,
Alex
DateSize
7/17/2013 | 2161 |
7/24/2013 | 1638 |
11/27/2013 | 1414 |
12/4/2013 | 1101 |
12/12/2013 | 1074 |
1/10/2014 | 1078 |
3/20/2014 | 966 |
4/21/2014 | 859 |
4/22/2014 | 1056 |
5/27/2014 | 995 |
6/5/2014 | 921 |
6/6/2014 | 881 |
6/9/2014 | 827 |
6/26/2014 | 836 |