简体   繁体   English

SQL减去查询中前一行的值的最佳方法?

[英]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. 表中的列是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. 从理论上讲,它只需按machineID和StartTime对表进行排序,然后采用当前行的StartTime并减去先前行的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: 从wildplasser发表评论后,我创建了以下查询:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM