2016-07-15 211 views
0

我有一個包含nazwa,wartosc,czas的進程數據的表。該表的數據看起來像this計算兩個記錄之間差異(時間)的總和 - mssql

現在我寫查詢:

;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],而不是本次輸出一行總和?

+0

由於其他列在所有行中都有不同的數據:如果結果減少爲單行,您希望在那裏顯示哪些信息? – Shnugo

+0

我會有關於所有時差的信息。 [Wsekundach] –

+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 
+0

我有一行錯誤: ; WITH cteNewRows AS ';'附近語法不正確。 –

+0

@ G.Dabrowski,查詢編輯。 –

+0

非常感謝,你能告訴我我怎樣才能做到,當最後一行有wartosc = 1而不是添加到[Wsekundach] 7.行的日期時間和'2016-07-14 22:30: 00.000' –

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; 

這樣做只是基於最大之和最小值是比總結中間和更高效。

相關問題