SQL - Operand data type datetime2 is invalid for subtract operator

后端 未结 2 1048
逝去的感伤
逝去的感伤 2021-01-20 02:11

I want to subtract the value of the first row from the value of the second row of column _timestamp (shown below). _number is the ordering column i

2条回答
  •  感情败类
    2021-01-20 02:51

    As mentioned in the comments, you can't subtract timestamps with - operator. Use DATEDIFF function instead. To get the difference of the current row and the next row's timestamps, use 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
    

    Edit: To update a column named diff per the OP's comment,

    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;
    

提交回复
热议问题