Question

I am new to this sql. I have a table as following which is order by date e.g.

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 -2   2  0  10-05-2014 9:12
14 -6   0 -2  10-05-2014 10:15

Where it has performed operation as (a-b) then (a-c) 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 (a-b) only

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

Was it helpful?

Solution

As you're on SQL Server 2008 you can utilize the ROW_NUMBER function:

SELECT 
   t1.WO,
   t1.x - t2.x,
   t1.y - t2.y,
   t1.z - t2.z,
   t1.date
FROM tab AS t1
JOIN 
 (
   SELECT tab.*,
      ROW_NUMBER()
      OVER (PARTITION BY WO 
      ORDER BY date) AS rn
   FROM tab
 ) AS t2
  ON t1.WO = t2.WO 
 AND t1.date <> t2.date
 AND t2.rn = 1

OTHER TIPS

This should do the trick (joining the table to itself), not sure about the performance though :

SELECT t1.WO , t2. date as myDate ,t2.X - t1.X as Xdiff, t2.Y - t1.Y as Ydiff, t2.Z - t1.Z as Zdiff
FROM (t as t1
JOIN t as t2
ON t1.WO = t2.WO
     AND t1.Date < t2.Date
     AND t1.Date IN (SELECT min(Date) FROM t WHERE t.WO = t1.WO));

Note that it doesn't only work with SQL Server.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top