I am trying to subtract the value of a previous row from the current row using SQL.
SELECT
rd.PONum,
od.OrderLine,
rd.PartNum,
p.PartDescription,
od.OrderNum,
rd.OurQty,
od.Number01 AS Reserved,
CASE WHEN rd.OurQty - od.Number01 > 0
THEN od.Number01
ELSE rd.OurQty END AS Allocated,
rd.OurQty - od.Number01 AS NewOurQty,
c.CustNum,
c.Name
FROM dbo.RcvDtl AS rd INNER JOIN
dbo.Part AS p ON rd.PartNum = p.PartNum INNER JOIN
dbo.OrderDtl AS od ON rd.PartNum = od.PartNum INNER JOIN
dbo.OrderHed AS oh ON od.OrderNum = oh.OrderNum INNER JOIN
dbo.Customer AS c ON od.CustNum = c.CustNum
WHERE (rd.PONum = 73)
AND (od.Number01 > 0)
AND (od.OpenLine = 1)
This returns the values:
PONum | OrderLine | PartNum | PartDescription | OrderNum | OurQty | Reserved | Allocated | NewOurQty | CustNum | Name
73 1 10050926 Example Description 62 55 35 35 20 1032 Sam Test
73 1 10050926 Example Description 63 55 6 6 49 496 Steve Test
But I want it to return:
PONum | OrderLine | PartNum | PartDescription | OrderNum | OurQty | Reserved | Allocated | NewOurQty | CustNum | Name
73 1 10050926 Example Description 62 55 35 35 20 1032 Sam Test
73 1 10050926 Example Description 63 55 6 6 14 496 Steve Test
In Row 1 the NewOurQty= 20 (55-35). Row 2 now needs to compute the NewOurQty for the current row by calculating NewOurQty (from row n-1) - reserved (from row n).
How can I retrieve the value from the previous row using SQL?
EDIT
I am using Microsoft SQL