I am trying to write a view in SQL Server 2012 where I calculate the 30 day moving sum for a set of transactions.
Current script:
SELECT CustNo, TransactionDate, TransactionAmount, SUM(TransactionAmount)
OVER (PARTITION BY CustNo ORDER BY TransactionDate) AS MovingAmount
FROM dbo.TransactionData
Data set:
CustNo TransactionDate TransactionAmount
1111 5/7/2015 3,000
1111 5/14/2015 3,000
2222 5/17/2015 100
1111 5/21/2015 3,000
1111 5/28/2015 3,000
3333 5/31/2015 11,000
1111 6/10/2015 3,000
Expected Result:
CustNo TransactionDate TransactionAmount MovingAmount
1111 5/7/2015 3,000 12,000
1111 5/14/2015 3,000 12,000
2222 5/17/2015 100 100
1111 5/21/2015 3,000 9,000
1111 5/28/2015 3,000 6,000
3333 5/31/2015 11,000 11,000
1111 6/10/2015 3,000 3,000
Other attempts:
SELECT CustNo, TransactionDate, TransactionAmount, SUM(TransactionAmount)
OVER (PARTITION BY CustomerNumber ORDER BY TransactionDate,
BETWEEN TransactionDate AND DATEADD(day, 30, TransactionDate))
AS MovingAmount
FROM dbo.TransactionData
I'm assuming the 12,000 in the first row of your desired result is a typo, and it should be 3,000. If I'm correct, your first query seems to be working fine, it's just hard to see without anorder byto the entire query:Create and populate sample table (Please save us this step in your future questions)
Going with Tab Alleman's interpretation of the question, It can't be done with the over clause, you need to use a correlated sub query:
Results:
You can see a live demo on rextester.