怎样找出出几个记录中,相隔时间最长的那个两个记录和相隔时间(多少分钟)
本帖最后由 linjimu 于 2013-05-23 17:36:38 编辑 怎样找出出几个记录中,相隔时间最长的那个两个记录和相隔时间(多少分钟)
比如:表T:
id RecordTime
1 2013-05-01 8:01
2 2013-05-01 9:30
3 2013-05-01 10:02
4 2013-05-01 11:23
找出4个记录的 RecordTime 相隔时间最大的那个记录和相隔时间。
1和2 相隔 89分钟 (1小时29分)
2和3 相隔 32分钟
3和4 相隔 81分钟 (1小时21分钟)
找到后,插入到另外一个表里面:表M:
TimeFrom TimeTo IntMaxTime
2013-05-01 8:01 2013-05-01 9:30 89
到时会用在存储过程里面,可能涉及到游标,临时表。
谢谢!
[解决办法]
declare @t table( id int,RecordTime datetime)
insert into @t
select 1,'2013-05-01 8:01' union all
select 2,'2013-05-01 9:30' union all
select 3,'2013-05-01 10:02' union all
select 4,'2013-05-01 11:23'
;with a as(
select top 100 percent a.id,a.RecordTime,
(select top 1 RecordTime from @t B where id<a.id order by id desc ) RecordTime_p
from @t A
order by id
)
select top 1 RecordTime_p TimeFrom,RecordTime TimeTo,datediff(minute,RecordTime_p,RecordTime) IntMaxTime
from a
order by IntMaxTime desc
12013-05-01 08:01:00.000189
*/
[解决办法]
declare @t table
(
id int,
RecordTime datetime
)
insert into @t
select 1,'2013-05-01 8:01' union all
select 2,'2013-05-01 9:30' union all
select 3,'2013-05-01 10:02' union all
select 4,'2013-05-01 11:23'
select top 1 a.RecordTime as TimeFrom,b.RecordTime as TimeTo,
datediff(minute,a.RecordTime,b.RecordTime)maxtime
from @t a,@t b where a.id+1 = b.id
order by datediff(minute,a.RecordTime,b.RecordTime) desc