我试图使用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
答案 0 :(得分:1)
您可以引入行号
SELECT @ROW := @ROW + 1 AS row, first_name
FROM users, (SELECT @ROW := 0) r;
并在子查询中添加列。然后添加join ON firstAlias.row=secondAlias.row+1
答案 1 :(得分:1)
也许这种技术很有用(这里用ROW N-1的值加上ROW N的值):
CREATE TABLE TEST(
source INT
)
INSERT INTO TEST VALUES(1)
INSERT INTO TEST VALUES(10)
INSERT INTO TEST VALUES(20)
INSERT INTO TEST VALUES(30)
INSERT INTO TEST VALUES(40)
INSERT INTO TEST VALUES(50)
/*HERE THE QUERY*/
WITH temp AS (
SELECT t.*,ROW_NUMBER() over (order by t.source) as row_num
FROM TEST t
)
SELECT
x.source,
x.source + ISNULL((SELECT y.source FROM temp y WHERE y.row_num = x.row_num - 1),0) AS SUM_ACUMULATE
FROM temp x
您可以尝试 here 。