I am working with Microsoft SQL Server 2012.
I have a table with Item transactions:
artcode transdate Qty transactionvalue
------------------------------------------------
M100 2010-11-24 6.00 179.40
M100 2010-11-24 -6.00 -179.4
M100 2010-11-25 100.00 2900.00
M100 2010-11-26 -1.00 -29
M100 2010-11-26 -5.00 -145
M100 2010-11-26 -1.00 -29
M100 2010-11-29 -5.00 -145
M100 2010-11-29 -3.00 -87
M100 2010-11-29 -1.00 -29
With this query I have managed to get the cumulative values in running order:
SELECT
TransDate, ArtCode, CumulativeQuantity, CumulativeValue
FROM
(SELECT
ArtCode,
SUM(CAST(REPLACE(REPLACE(NULLIF(Qty, ''), ',', '.'), ' ', '') AS float)) OVER (PARTITION BY artcode ORDER BY transdate) AS CumulativeQuantity,
SUM(CAST(REPLACE(REPLACE(NULLIF(TotCostPrice, ''), ',', '.'), ' ', '') AS FLOAT)) OVER (PARTITION BY artcode ORDER BY transdate) AS CumulativeValue,
TransDate
FROM
stage_itemhistory
WHERE
artcode = 'm100' AND stockaffect = 1) S
GROUP BY
TransDate, ArtCode, CumulativeQuantity, CumulativeValue
This returns:
TransDate ArtCode CumulativeQuantity CumulativeValue
--------------------------------------------------------
2010-11-24 M100 0 0
2010-11-25 M100 100 2900
2010-11-26 M100 93 2697
2010-11-29 M100 84 2436
Which is quite close to what I am after, the only thing missing is the dates between, that would have the previous dates cumulative values. So it would look like this:
TransDate ArtCode CumulativeQuantity CumulativeValue
--------------------------------------------------------
2010-11-24 M100 0 0
2010-11-25 M100 100 2900
2010-11-26 M100 93 2697
2010-11-27 M100 93 2697
2010-11-28 M100 93 2697
2010-11-29 M100 84 2436
Any and all help would be greatly appreciated! Thank you in advance.