Question

I want to perform a subtraction on following table with a query.

WO  X   Y  Z   Date
12  10 10  12  10-05-2014 7:10
12  8  10  12  10-05-2014 8:10
12  8  12  12  10-05-2014 9:12
14  16 10  14  10-05-2014 10:10
14  10 10  12  10-05-2014 10:15

Now i want to perform an operation so that the expected result would be

WO  X   Y  Z   Date
12 -2   0  0  10-05-2014 8:10
12  0   2  0  10-05-2014 9:12
14 -6   0 -2  10-05-2014 10:15

Where it has performed operation as (b-a) then (c-b) and so on for each WO. So from above example it took first row of WO 12 with mindate and performed subtraction of column x, y and z with second row. And so third row. Same happened with WO 14 but as there are only two lines so (b-a) only

Is there any method which can achieve this result. I dont want to used cursor or so.

Was it helpful?

Solution

Consider the table name as TEST

WITH TABLE1 (ID, WO, X, Y, Z, date) AS 
(
 SELECT ROW_NUMBER() OVER (PARTITION BY TEST.WO ORDER BY TEST.WO) AS ID,
        TEST.*
   FROM TEST
),
TABLE2 (ID, WO, X, Y, Z, date) AS 
(
 SELECT ROW_NUMBER() OVER (PARTITION BY TEST.WO ORDER BY TEST.WO) AS ID,
        TEST.*
   FROM TEST
)
 SELECT TABLE1.WO,
        (TABLE1.X-TABLE2.X), 
        (TABLE1.Y-TABLE2.Y), 
        (TABLE1.Z-TABLE2.Z),
        TABLE1.date
   FROM TABLE1
        LEFT JOIN TABLE2 ON TABLE1.ID = (TABLE2.ID + 1)
              AND TABLE1.WO = TABLE2.WO
  WHERE TABLE2.ID IS NOT NULL
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top