两个记录之间的计算差值(时间)的总和 - MSSQL



我有一个包含nazwa,wartosc,czas的过程数据的表。表数据如下所示

现在我写了查询:

;WITH [cteRows] AS
(
    SELECT  [nazwa],
            [wartosc],
            [czas],
            ROW_NUMBER() OVER (ORDER BY [czas]) AS [RowNumber]
    FROM [test].[dbo].[coldbox7]
    WHERE [nazwa] = 'coldbox7/WymianaDanychDB/Hydraulic' 
    AND [czas] >= '2016-07-14 22:00:00.000' 
    AND [czas] <= '2016-07-14 22:30:00.000'
) 
SELECT  mc.[RowNumber],
        mc.[czas],
        mc.[nazwa],
        mc.[wartosc],
        DATEDIFF(SECOND, mc.[czas], ISNULL(mp.[czas], mc.[czas])) AS [Wsekundach]
FROM [cteRows] mc 
LEFT JOIN [cteRows] mp 
    ON mc.[RowNumber] = mp.[RowNumber] + 1 
WHERE mc.[wartosc] = 0 

输出如下所示:

我有问题:如何使 [Wsekundach] 的一行总和而不是当前输出?

尝试以下操作:

;WITH [cteRows] AS
(
    SELECT  [nazwa],
            [wartosc],
            [czas],
            ROW_NUMBER() OVER (ORDER BY [czas]) AS [RowNumber]
    FROM [test].[dbo].[coldbox7]
    WHERE [nazwa] = 'coldbox7/WymianaDanychDB/Hydraulic' 
    AND [czas] >= '2016-07-14 22:00:00.000' 
    AND [czas] <= '2016-07-14 22:30:00.000'
)
, cteNewRows AS
(
    SELECT  mc.[RowNumber],
            mc.[czas],
            mc.[nazwa],
            mc.[wartosc],
            DATEDIFF(SECOND, mc.[czas], ISNULL(mp.[czas], mc.[czas])) AS [Wsekundach]
    FROM [cteRows] mc 
    LEFT JOIN [cteRows] mp  ON mc.[RowNumber] = mp.[RowNumber] + 1 
    WHERE mc.[wartosc] = 0 
)
SELECT  SUM(Wsekundach) AS SumOfWsekundach
FROM    cteNewRows

如果你想要一行是差异,我认为你可以使用一个更简单的查询:

      SELECT DATEDIFF(SECOND, MIN(c.[czas]), MAX(c.[czas]) 
      FROM [test].[dbo].[coldbox7] c
      WHERE [nazwa] = 'coldbox7/WymianaDanychDB/Hydraulic' AND
            [czas] >= '2016-07-14 22:00:00.000' AND
            [czas] <= '2016-07-14 22:30:00.000' AND
            c.[wartosc] = 0;

仅根据最大值和最小值进行求和比对中间总和求和更有效。

相关内容

  • 没有找到相关文章

最新更新