I have following input for which I need to calculate the sum of values for previous x number of weeks for each category.
If the x is 3 the output would look like this:
Note that the last value is 49 because it added only last two week's values to the current week since x=3.
I am looking to write the SQL as a stored procedure and need some help on appropriate ways of doing this.
With the help from @sp_BlitzErik I tried to use LAG but couldn't quite get where I need to. Here is my query:
SELECT category
,year
,week
,value
,(
LAG(value, 1, 0) OVER (
ORDER BY category
,year
,week
) + LAG(value, 2, 0) OVER (
ORDER BY category
,year
,week
) + value
) AS cumulative_value
FROM valuedata
And the output is not quite correct yet:
Best Answer
On SQL Server 2014 and 2016 1 you can use a
WINDOW
function (i.e. anOVER
clause) to perform what you want:And this is the result you'll get:
NOTE that the
x = 3
of your example gets translated to (the current row and the2 preceding
ones).If, for some reason, you can't use the
OVER
clause, you can still compute the same results using some (quite convoluted) subqueries:Check it all at dbfiddle here
If you want to use
@x
instead of3
, you can do so:dbfiddle here
1) Can't test with SQL Server 2012 because I don't have one. The documentation from MS SQL Server indicate it should be available since version 2008.