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

时间:2012-12-06 00:23:40

标签: sql sql-server

我正在尝试计算数据库中丢失的机器总时间。表中的列是MachineID,即PlantID,StartTime,EndTime。

理论上,它只是按机器ID和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

1 个答案:

答案 0 :(得分:1)

这是我带来的结果查询:)

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