Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

OVER FUNCTION

$
0
0

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/20132161
7/24/20131638
11/27/20131414
12/4/20131101
12/12/20131074
1/10/20141078
3/20/2014966
4/21/2014859
4/22/20141056
5/27/2014995
6/5/2014921
6/6/2014881
6/9/2014827
6/26/2014836

Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>