[英]SQL best way to subtract a value of the previous row in the query?
我正在尝试计算数据库中丢失的机器总时间。 表中的列是MachineID aka PlantID,StartTime,EndTime。
从理论上讲,它只需按machineID和StartTime对表进行排序,然后采用当前行的StartTime并减去先前行的EndTime。
这是我目前有效的查询:
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
我的问题是:是否有更好的方法(更简洁)来实现此查询的相同结果?
谢谢您的帮助。
编辑:
从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
这是我去的结果查询:)
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.