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

后端 未结 1 1174
醉话见心
醉话见心 2021-01-23 21:18

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 t

相关标签:
1条回答
  • 2021-01-23 21:30

    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
    
    0 讨论(0)
提交回复
热议问题