1

I'm trying to calculate the total lost machine time in the database. The columns in the table are MachineID aka PlantID, StartTime, EndTime.

In theory its simply sort the table by machineID and by StartTime then take the StartTime of the current row and subtract the previous rows EndTime.

Here is my current query that works:

SELECT SUM([StartTime] - [EndTime]) AS TotalLostTime  
FROM(SELECT * 
     FROM (SELECT ROW_NUMBER() OVER (ORDER BY [PlantID], [StartTime]) AS [Row],
                  [MachineRecords].PlantID , [MachineRecords].EndTime 
           FROM [MachineRecords]) AS a 
     JOIN (SELECT * 
           FROM (SELECT ROW_NUMBER() OVER (ORDER BY [PlantID], 
                                                        [StartTime]) AS [Row1],
                        [MachineRecords].PlantID as PlantID1 , 
                        [MachineRecords].StartTime 
                 FROM [MachineRecords]) as b) m 
     ON m.PlantID1 = a.[PlantID] 
        AND a.[Row] = m.[Row1]-1) lostTimeQuery

My question is: Is there a better(more consise) way of achieving the same result of this query?

Thanks for the help.

EDIT:

After the comment from wildplasser i've created this query:

SELECT SUM(a.StartTime - a.LagEnd) as LostTime 
FROM (SELECT [PlantID], [StartTime], [EndTime], 
             LAG([PlantID]) OVER (ORDER BY PlantID, StartTime) LagPlantID,
             LAG([EndTime]) OVER (ORDER BY PlantID, StartTime) LagEnd 
      FROM MachineRecords) a 
WHERE a.PlantID = a.LagPlantID
7
  • 2
    A window function, such as lag() ? Dec 6, 2012 at 0:25
  • This does seem to be what im after :)
    – Anthbs
    Dec 6, 2012 at 0:29
  • 1
    What RDBMS are you using? Not all of them support that particular function. Also, could we get a sample schema? For example, if you have a (stored) sequence number per plantId you don't need to calculate it on the fly. Dec 6, 2012 at 0:47
  • 1
    From the ugly [FieldNames] you can conclude that he uses one of the Microsoft products. BTW: row_number() is also a window function but you'll have to handle the begin-of-group case (LEFT join+ COALESCE, basically) Dec 6, 2012 at 0:48
  • 1
    I didn't think plantId itself was a sequence... Oh, if you've figured out the answer yourself, it's perfectly acceptable to post it as an answer. Dec 6, 2012 at 1:05

1 Answer 1

1

This was the resulting query I went with :)

SELECT SUM(a.StartTime - a.LagEnd) as LostTime 
FROM (SELECT [PlantID], [StartTime], [EndTime], 
             LAG([PlantID]) OVER (ORDER BY PlantID, StartTime) LagPlantID,
             LAG([EndTime]) OVER (ORDER BY PlantID, StartTime) LagEnd 
      FROM MachineRecords) a 
WHERE a.PlantID = a.LagPlantID

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.