我想從當前行減去使用SQL的前一行的值。使用前一行的值的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)
這將返回值:
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
但我想它返回:
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
第1行中NewOurQty = 20(55-35)。第2行現在需要通過計算NewOurQty(從第n-1行) - 保留(從第n行)計算當前行的NewOurQty。
如何使用SQL從前一行檢索值?
編輯
我使用的是Microsoft SQL
像'lag()'這樣的WINDOW函數就足夠了,恕我直言。 – wildplasser
您正在使用哪些DBMS? Postgres的?甲骨文? –
我正在使用MSSQL – samb90