问题描述
我有一个包含 StartDate 列的表,我想计算两个连续记录之间的时间差.
I have a table with column StartDate, I want to calculate the time difference between two consecutive record.
谢谢.
@ Mark Byers 和@ Yahia,我有请求表作为 requestId, startdate
@ Mark Byers and @ Yahia, I have request table as requestId, startdate
requestId startdate
1 2011-10-16 13:15:56
2 2011-10-16 13:15:59
3 2011-10-16 13:15:59
4 2011-10-16 13:16:02
5 2011-10-16 13:18:07
我想知道 requestid 1 & 之间的时差是多少2, 2 &3, 3 &4等.我知道我需要在桌子上自我加入,但我没有得到正确的条款.
and i want to know what is the time difference between requestid 1 & 2, 2 & 3, 3 & 4 and so on. i know i will need self join on table, but i am not getting correct on clause.
推荐答案
要实现您的要求,请尝试以下操作(从 OP 编辑后更新):
To achieve what you are asking try the following (UPDATE after edit from OP):
SELECT A.requestid, A.starttime, (B.starttime - A.starttime) AS timedifference
FROM MyTable A INNER JOIN MyTable B ON B.requestid = (A.requestid + 1)
ORDER BY A.requestid ASC
如果 requestid
不是连续的,那么你可以使用
IF requestid
is not consecutive then you can use
SELECT A.requestid, A.starttime, (B.starttime - A.starttime) AS timedifference
FROM MyTable A CROSS JOIN MyTable B
WHERE B.requestid IN (SELECT MIN (C.requestid) FROM MyTable C WHERE C.requestid > A.requestid)
ORDER BY A.requestid ASC
这篇关于计算两行之间的时间差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!