怎样找出出几个记录中,相隔时间最长的那个两个记录和相隔时间(多少分钟)
本帖最后由 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
------解决方案--------------------SELECT TOP 1 *,DATEDIFF(mi,a.[RecordTime],b.[RecordTime]) AS df FROM #tb a, #tb b
WHERE a.id=b.id-1
ORDER BY df DESC
这样可以吗?恐怕你的id不连续
------解决方案--------------------2005 用 row_number 生成连续的id 就可以了
--> 测试数据:#tb
IF OBJECT_ID('TEMPDB.DBO.#tb') IS NOT NULL DROP TABLE #tb
GO
CREATE TABLE #tb([id] INT,[RecordTime] DATETIME)
INSERT #tb
SELECT 1,'2013-05-01 8:01' UNION ALL
SELECT 3,'2013-05-01 9:30' UNION ALL
SELECT 5,'2013-05-01 10:02' UNION ALL
SELECT 9,'2013-05-01 11:23'
--------------开始查询--------------------------
;WITH cte AS
(
SELECT *,row_id=ROW_NUMBER() OVER(ORDER BY [id]) FROM #tb
)
SELECT TOP 1 a.*,DATEDIFF(mi,a.[RecordTime],b.[RecordTime]) AS df FROM cte a, cte b
WHERE a.row_id=b.row_id-1
ORDER BY df DESC
----------------结果----------------------------
/*
id RecordTime row_id df