我想在sql
中显示累积时差。这是时间戳列。时间差应采用累积形式而不使用临时表,但id
我们可以使用ROW_NUMBER()
:
Timestamp
2015-05-20 11:23:34.853
2015-05-20 11:21:40.790
2015-05-20 11:20:12.447
2015-05-20 11:19:31.723
2015-05-20 11:19:10.993
结果应该是这样的:
TimeDifference
00:00:00
00:01:54
00:01:28
00:00:41
00:00:21
答案 0 :(得分:4)
您可以将DATEDIFF
与CONVERT
一起用于Time
,并根据时间戳的顺序使用自我加入来实现此目的。像这样(对于SQL Server 2008)。
;WITH cte as
(
select '2015-05-20 11:23:34.853' ts
union all select '2015-05-20 11:21:40.790'
union all select '2015-05-20 11:20:12.447'
union all select '2015-05-20 11:19:31.723'
union all select '2015-05-20 11:19:10.993'
), cte2 as
(
SELECT *,ROW_NUMBER()OVER(ORDER BY ts DESC) rn
FROM cte
)
select t1.ts,t2.ts,CONVERT(TIME,DATEADD(s,ISNULL(DATEDIFF(s,t1.ts,t2.ts),0),0)) diff
from cte2 t1 LEFT JOIN cte2 t2 on t1.rn = t2.rn + 1
<强>输出强>
ts ts diff
2015-05-20 11:23:34.853 NULL 00:00:00.0000000
2015-05-20 11:21:40.790 2015-05-20 11:23:34.853 00:01:54.0000000
2015-05-20 11:20:12.447 2015-05-20 11:21:40.790 00:01:28.0000000
2015-05-20 11:19:31.723 2015-05-20 11:20:12.447 00:00:41.0000000
2015-05-20 11:19:10.993 2015-05-20 11:19:31.723 00:00:21.0000000
如果您使用的是SQL 2012,则可以像这样使用LAG
/ LEAD
SELECT CONVERT(TIME,DATEADD(s,ISNULL(DATEDIFF(s,ts,LAG(ts)over(order by ts DESC)),0),0))
FROM cte
ORDER BY ts DESC
答案 1 :(得分:1)
您可以对行进行编号,然后使用left join
计算差异:
DECLARE @t TABLE ( d DATETIME )
INSERT INTO @t
VALUES ( '2015-05-20 11:23:34.853' ),
( '2015-05-20 11:21:40.790' ),
( '2015-05-20 11:20:12.447' ),
( '2015-05-20 11:19:31.723' ),
( '2015-05-20 11:19:10.993' );
WITH cte
AS ( SELECT d ,
ROW_NUMBER() OVER ( ORDER BY d DESC ) AS rn
FROM @t
)
SELECT CAST(ISNULL(c2.d - c1.d, 0) AS TIME(0)) TimeDifference
FROM cte c1
LEFT JOIN cte c2 ON c2.rn + 1 = c1.rn
输出:
TimeDifference
00:00:00
00:01:54
00:01:28
00:00:41
00:00:21
但请注意,时间类型最长可达24小时。