简体   繁体   中英

SQL Query using value from previous row

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

You can introduce a row number

SELECT @ROW := @ROW + 1 AS row, first_name
FROM users, (SELECT @ROW := 0) r;

and add the column in a subquery. Then add join ON firstAlias.row=secondAlias.row+1

Maybe this technique will be useful (here add the value of ROW N with the value of ROW N-1):

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

You can try this here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM