日期:2014-05-18 浏览次数:20612 次
--没有看明白...是不是这样一个思路 ;with cte as ( select rownumber() over(order by date_time) as sn,date_time,number from tb ) select a.date_time,a.number,datediff(hh,a.date_time,b.date_time) as difftime,(b.number-a.number) as number_diff from cte as a join cte as b on a.sn=b.sn+1 --没有在分析器里写..因为我不懂你的思路.不知道写的对不对..大致就这个思路
------解决方案--------------------
IF OBJECT_ID('tempdb..#FF') IS NOT NULL DROP TABLE #FF GO CREATE TABLE #FF (Number INT,Date_Time DATETIME) INSERT #FF SELECT 1,'2012-1-7 02:05:57' UNION ALL SELECT 2,'2012-1-7 03:38:52' UNION ALL SELECT 4,'2012-1-7 04:17:07' UNION ALL SELECT 3,'2012-1-7 04:48:32' UNION ALL SELECT 2,'2012-1-7 09:18:34' UNION ALL SELECT 1,'2012-1-7 11:55:38' UNION ALL SELECT 1,'2012-1-7 16:47:56' DECLARE @NUMBER INT,@QSSJ DATETIME,@JZSJ DATETIME SELECT @NUMBER = 1,@QSSJ = '2012-1-7 9:00:00',@JZSJ = '2012-1-8 8:00:00' SELECT A.Number, A.Date_Time, B.Date_Time, '分钟相差' = CAST(DATEDIFF(hh,B.Date_Time,A.Date_Time) AS VARCHAR(5)) +'小时'+CAST(DATEDIFF(mi,B.Date_Time,A.Date_Time)%60 AS VARCHAR(10))+'分' +CAST(DATEDIFF(ss,B.Date_Time,A.Date_Time)%60 AS VARCHAR(10))+'秒' FROM ( SELECT Number = MAX(Number),Date_Time = MAX(Date_Time),ROW = 0 FROM #FF WHERE Date_Time < @QSSJ AND Number = 1 UNION ALL SELECT Number,Date_Time,ROW = ROW_NUMBER() OVER(ORDER BY(Date_Time ) ) FROM #FF WHERE Date_Time BETWEEN @QSSJ AND @JZSJ AND Number = 1 ) A JOIN ( SELECT Number = MAX(Number),Date_Time = MAX(Date_Time),ROW = 0 FROM #FF WHERE Date_Time < @QSSJ AND Number = 1 UNION ALL SELECT Number,Date_Time,ROW = ROW_NUMBER() OVER(ORDER BY(Date_Time ) ) FROM #FF WHERE Date_Time BETWEEN @QSSJ AND @JZSJ AND Number = 1 ) B ON A.ROW = B.ROW+1 /* Number Date_Time Date_Time 时间相差 ----------- ----------------------- ----------------------- --------------------------------- 1 2012-01-07 11:55:38.000 2012-01-07 02:05:57.000 9小时50分41秒 1 2012-01-07 16:47:56.000 2012-01-07 11:55:38.000 5小时52分18秒 */
------解决方案--------------------
DECLARE @NUMBER INT,@QSSJ DATETIME,@JZSJ DATETIME SELECT @NUMBER = 1,@QSSJ = '2012-1-7 9:00:00',@JZSJ = '2012-1-8 8:00:00' SELECT A.Number, A.Date_Time, B.Date_Time, '时间相差' = CAST(DATEDIFF(hh,B.Date_Time,A.Date_Time) AS VARCHAR(5)) +'小时'+CAST(DATEDIFF(mi,B.Date_Time,A.Date_Time)%60 AS VARCHAR(10))+'分'