I am trying to use previous records calculated value to perform current record calculations.
In the below image, we have written a small query which calculates the closing stock of all days. The calculated closing stock value of day 1 should be used as Actual stock for day 2 and similarly the calculated closing stock value of day 2 should be used as Actual stock for day 3 and so on till the end of the dates. We would like to perform this logic in a single select query. We tried to use SQL LAG(), BOUNDED Preceding but nothing turned to be positive.
You can try this:
WITH CTE AS (
SELECT
ROW_NUMBER() OVER(ORDER BY PART_NUMBER, DATE) AS Rownum,
PART_NUMBER, DATE, ACTUALSTOCK, GROSS, BACKLOG, RECEIPT,
SUM(ACTUALSTOCK - (GROSS + BACKLOG) + RECEIPT) OVER (ORDER BY PART_NUMBER, DATE) AS CLOSINGSTOCK
FROM Tbl_PV_Parts_Dtl_MGMT_cur
WHERE PART_NUMBER = '0112107261' AND
DATE BETWEEN '20151021' AND '20151031')
SELECT
PART_NUMBER, DATE,
CASE WHEN Rownum = 1 THEN ACTUALSTOCK ELSE LAG(CLOSINGSTOCK) OVER(ORDER BY Rownum) END,
GROSS, BACKLOG, RECEIPT,
CLOSINGSTOCK
FROM CTE
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments