SQL - 操作数数据类型datetime2对减法运算符无效

时间:2017-03-20 15:49:30

标签: sql sql-server-2008

我想从列_timestamp的第二行的值中减去第一行的值(如下所示)。 _number是我数据中的排序列。

enter image description here

并将结果放在名为 diff 的新列中。我已尝试使用以下查询

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 个答案:

答案 0 :(得分:4)

如评论中所述,您无法使用-运算符减去时间戳。请改用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

编辑:根据OP的评论,为update一个名为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;

答案 1 :(得分:1)

使用datetime2

确实不可行
DECLARE @t1 DATETIME2(7) = '2020-01-01 13:20:00.000'
DECLARE @t2 DATETIME2(7) = '2020-01-01 13:22:23.000'
 
SELECT  CONVERT(VARCHAR(50),@t2 - @t1, 108)

>> Operand data type datetime2 is invalid for subtract operator.

但是当转换为datetime时,它会得到不错的结果;-)

DECLARE @t1 DATETIME2(7) = '2020-01-01 13:20:00.000' 
DECLARE @t2 DATETIME2(7) = '2020-01-01 13:22:23.000'

SELECT  CONVERT(VARCHAR(50), CONVERT(DATETIME, @t2) - CONVERT(DATETIME, @t1), 108)

>> 00:02:23