如何计算时间戳列表之间的持续时间

时间:2015-01-30 20:17:31

标签: sql time timestamp duration

我有一个包含时间戳列表的表,我想计算时间戳之间的持续时间 表格列表如下所示

MYTIME
2015-01-30-08.12.51.141000
2015-01-30-08.12.51.142000
2015-01-30-08.12.51.142000
2015-01-30-08.12.51.162000
2015-01-30-08.12.51.170000
2015-01-30-08.12.51.290000

我想要的结果是

first timestamp next timestamp duration in microseconds
2015-01-30-08.12.51.141000 2015-01-30-08.12.51.142000 1000
2015-01-30-08.12.51.142000 2015-01-30-08.12.51.142000 0000
2015-01-30-08.12.51.142000 2015-01-30-08.12.51.162000 20000

我正在使用DB2 for i SQL但不确定如何使用数据透视表或CTE进行操作?

3 个答案:

答案 0 :(得分:1)

它依赖于您使用的SQL服务器。它是否实现了Window Functions?

这将是线之间的操作。上一个和下一个时间戳差异。

在MS SQL 2008中:

WITH AUXILIERY_TBL AS (
    SELECT 
      A.[Time_Stamp]
     ,ROW_NUMBER() OVER (ORDER BY A.[Time_Stamp]) AS Ordr
      FROM [Time_Stamps_TBL] AS A
)

SELECT 
 A.[Time_Stamp] 
,DATEDIFF(MINUTE ,B.[Time_Stamp] ,A.[Time_Stamp] ) AS Duration_Minutes
FROM AUXILIERY_TBL AS A
LEFT JOIN AUXILIERY_TBL AS B
       ON (A.Ordr=(B.Ordr+1))

在MS SQL 2012/14中,不需要临时表就会容易得多:

SELECT
 A.[Time_Stamp]
,DATEDIFF(MINUTE, (LAG(A.[Time_Stamp]) OVER (ORDER BY A.[Time_Stamp])), A.[Time_Stamp]) AS Duration_Minutes
FROM [Time_Stamps_TBL] AS A

您可以将DATEDIFF功能从几分钟更改为几小时或几秒,更适合您。

答案 1 :(得分:0)

我没有DB2数据库,但知道DB2也有一个ROW_NUMBER()函数。所以你可以尝试应用以下方法......(它适用于MS SQL)

CREATE TABLE #temp (dt datetime);

INSERT INTO #temp 
SELECT getutcdate() 
UNION ALL 
SELECT dateadd(ms, 7, getutcdate())
UNION ALL 
SELECT dateadd(s, 1, getutcdate())
UNION ALL 
SELECT dateadd(s, 3, getutcdate());

SELECT t1.dt as datetime1, t2.dt as datetime2, DATEDIFF(ms, t1.dt, t2.dt) as diff
FROM (SELECT dt, ROW_NUMBER() OVER(ORDER BY dt)+1 as rn FROM #temp) t1
INNER JOIN (SELECT dt, ROW_NUMBER() OVER(ORDER BY dt) as rn FROM #temp) t2
ON t1.rn = t2.rn

DROP TABLE #temp;

结果:

datetime1   datetime2   diff
2015-01-30 20:57:59.053 2015-01-30 20:57:59.060 6
2015-01-30 20:57:59.060 2015-01-30 20:58:00.053 993
2015-01-30 20:58:00.053 2015-01-30 20:58:02.053 2000

答案 2 :(得分:0)

这是我的DB2解决方案: 我有一个表格,其中一列填充了标签和时间戳; 首先,我创建了一个CTE来过滤我想要的记录,然后我提取了标签和时间戳以及新创建的排名列。 然后使用此CTE表我使用等级加1到2然后2到3等来获得我的持续时间。 *感谢米兰让我朝着正确的方向前进。

用TagTimeTable(myTag,myTime,myRank)作为 (选择子字符串(SPOOLRCD FROM 34 FOR 6)AS mytag,CAST(substring(SPOOLRCD FROM 60 FOR 26)AS TIMESTAMP)AS mytime,ROW_NUMBER()OVER(ORDER BY substring(SPOOLRCD FROM 60 FOR 26))as myrank 来自MYLIB.SPOOLTBL 在哪里SPOOLRCD喜欢'%DSPLY%' 按时间排序 )

SELECT cast('0001-01-01 00:00:00.000'作为时间戳)+ TIMESTAMPDIFF(1,CHAR(time2.myTime - time1.myTime))MICROSECOND as TIME_IN_MICROSECONDS, TIME1.MYTIME, TIME2.MYTIME 从     TagTimeTable TIME1     内部联接     TagTimeTable TIME2 ON(TIME1.myRank = TIME2.myRank-1);