2017-03-20 84 views
0

我想從列_timestamp(如下所示)的第二行的值中減去第一行的值。 _number是我數據中的排序列。SQL - 操作數數據類型datetime2對於減法運算符無效

enter image description here

,並把結果在一個新列名爲差異。我試着用以下查詢

use dbtest 

select t2._number, t2._timestamp, 
coalesce(t2._timestamp - 
    (select t1._timestamp from dbo.tcp t1 where t1._number = t2._number + 1), t2._timestamp) as diff 
from dbo.tbl t2 

但我收到以下錯誤。

Msg 8117, Level 16, State 1, Line 4 
Operand data type datetime2 is invalid for subtract operator. 

任何提示將不勝感激。我有一個巨大的記錄,我想自動將它應用於整個列。我正在使用SQL Sever 2008.

+2

列,請參見DATEDIFF函數https://msdn.microsoft.com/en-us/library/ms189794.aspx – Serg

+0

使用datediff https://msdn.microsoft.com/zh-cn/library/ms189794.aspx你只需要兩行或全部記錄? – McNets

+0

不,我想將它應用於所有記錄(大約300,000行) –

回答

2

正如評論中所述,您不能用-運算符減去時間戳。改用DATEDIFF函數。 要獲取當前行和下一行的時間戳的差異,請使用OUTER APPLY

select t2._number,t2._timestamp, 
datediff(microsecond,t2._timestamp,t1._timestamp) as diff 
from dbo.tbl t2 
outer apply (select t1._timestamp 
      from dbo.tcp t1 
      where t1._number = t2._number + 1) t1 

編輯:update命名%的OP的評論DIFF

with cte as (   
select t2._number,t2._timestamp, t2.diff, 
datediff(microsecond,t2._timestamp,t1._timestamp) as diff_col 
from t t2 
outer apply (select t1._timestamp 
      from t t1 
      where t1._number = t2._number + 1) t1 
    ) 
update cte set diff=diff_col; 
+0

您的意思是用上面的查詢結果更新'diff'列嗎? –

+1

@DestaHaileselassieHagos ..查看編輯..你可以使用cte來更新。 –

相關問題