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

问题描述 投票:0回答:4

我有一张这样的桌子:

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
sql sql-server datediff
4个回答
12
投票

这个怎么样:

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

换句话说,您可以减去两个

datetime
值并将结果转换为时间。然后您可以按照自己喜欢的方式格式化结果。


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

0
投票

也许有点hacky:

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

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


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
© www.soinside.com 2019 - 2024. All rights reserved.