2013-07-17 51 views
0

我想從當前行減去使用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

+1

像'lag()'這樣的WINDOW函數就足夠了,恕我直言。 – wildplasser

+0

您正在使用哪些DBMS? Postgres的?甲骨文? –

+0

我正在使用MSSQL – samb90

回答

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

1

您可以引入一個行號

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

,並在子查詢中添加列。然後加入join ON firstAlias.row=secondAlias.row+1

+0

這是用於Sql Server的嗎? –

相關問題