简体   繁体   中英

SQL best way to subtract a value of the previous row in the query?

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

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

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