计算两个连续行之间的时差

时间:2016-10-05 15:19:10

标签: sql datediff

我有一张这样的表:

RecordID     TransDate
1            05-Oct-16 9:33:32 AM
2            05-Oct-16 9:33:37 AM
3            05-Oct-16 9:33:41 AM
4            05-Oct-16 9:33:46 AM
5            05-Oct-16 9:33:46 AM

我需要获得连续TransDate值之间的差异。我正在使用SQL Server 2014,并且知道使用LAG函数执行此操作的方法,但我不知道如何执行此操作。

我需要这个输出:

RecordID     TransDate              Diff
1            05-Oct-16 9:33:32 AM   0:00:00
2            05-Oct-16 9:33:37 AM   0:00:05
3            05-Oct-16 9:33:41 AM   0:00:04
4            05-Oct-16 9:33:46 AM   0:00:05
5            05-Oct-16 9:33:46 AM   0:00:00

有什么想法吗?

提前致谢!

4 个答案:

答案 0 :(得分:3)

这个怎么样:

select recordid, transdate,
       cast( (transdate - lag(transdate) over (order by transdate)) as time) as diff
from t;

换句话说,您可以减去两个datetime值并将结果转换为时间。然后,您可以根据需要格式化结果。

答案 1 :(得分:1)

非滞后/领导方法......

select T1.recordId, T1.TransDate, datediff(ss, T1.TransDate, T2.Transdate) as Diff
from Table1 T1
left join Table1 T2
on T1.Recordid = T2.RecordId +1

答案 2 :(得分:0)

也许有点hacky:

SELECT RecordId / 2 AS id, min(TransDate) AS TransDate, max(TransDate) - min(TransDate) AS Diff GROUP BY RecordId / 2

未经测试,因为我现在没有可用的SQL Server。

答案 3 :(得分:0)

尝试创建游标以获取日期差。

--- Query to get date difference between two rows 

declare @table table (olddate datetime, newdate datetime)
create table #table (olddate datetime, newdate datetime)

DECLARE db_cursor CURSOR FOR 

  SELECT  CONVERT(date,[utl_recycle_date] ) as RecycleDate
  FROM XYZ
  WHERE account_number = '6900' AND match_status = 'F' 
  AND [utl_recycle_date] IS NOT NULL
  AND [utl_recycle_date] > '11/01/2018'
  GROUP BY DATEDIFF(DAY, CONVERT(date,[utl_recycle_date] ), CONVERT(date, GETDATE())),CONVERT(date,[utl_recycle_date] )
  ORDER BY 1

DECLARE @RecycleDate datetime 
DECLARE @NewDate datetime 

OPEN db_cursor 

FETCH next FROM db_cursor INTO @RecycleDate 

WHILE @@FETCH_STATUS = 0 
  BEGIN 

      FETCH next FROM db_cursor INTO @NewDate

      insert INTO #table (olddate, newdate) values (cast(@RecycleDate as date), cast(@NewDate as date))
      set @RecycleDate = @NewDate

  END 

CLOSE db_cursor 

DEALLOCATE db_cursor 

select 
olddate, newdate,
CASE 
  WHEN DATEDIFF(DAY, olddate, newdate) = 0 THEN 1 
  WHEN DATEDIFF(DAY, olddate, newdate) > 0 THEN DATEDIFF(DAY, olddate, newdate)
  END AS RecyclerFrequency  

FROM #table

drop table #table