两个记录之间的计算差异(时间)之和 - mssql

时间:2016-07-15 10:17:44

标签: sql sql-server datetime

我有一个包含过程数据的表,其中包含nazwa,wartosc,czas。表格数据类似于this

现在我写了查询:

;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 

并输出look like:

我有疑问: 如何在[Wsekundach]中输入一行而不是当前输出?

2 个答案:

答案 0 :(得分:0)

请尝试以下操作:

;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

答案 1 :(得分:0)

如果你想要一行不同,我认为你可以使用更简单的查询:

      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;

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