日期:2014-05-18 浏览次数:21175 次
select datediff(mi,b.start_time ,a.end_time) from (select id=row_number()over(order by getdate()),* from tb)a, (select id=row_number()over(order by getdate()),* from tb)b where a.id=b.id-1
------解决方案--------------------
---------------------------------------------- -- Author : htl258(Tony) -- Date : 2010-05-10 11:37:00 -- Version: Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86) -- Jul 9 2008 14:43:34 -- Copyright (c) 1988-2008 Microsoft Corporation -- Developer Edition on Windows NT 5.1 <X86> (Build 2600: Service Pack 3) -- Blog : http://blog.csdn.net/htl258 ---------------------------------------------- --> 生成测试数据表: [tb] IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb] GO CREATE TABLE [tb] ([job] [nvarchar](20),[gx_id] [int],[start_time] [datetime],[end_time] [datetime]) INSERT INTO [tb] SELECT '0001011-3-1','10','2010-5-10 10:00:00','2010-5-10 15:23:10' UNION ALL SELECT '0002695-1-2','30','2010-5-10 15:30:00','2010-5-10 18:00:00' UNION ALL SELECT '0003625-6-2','60','2010-5-11 07:20:05','2010-5-11 11:30:00' UNION ALL SELECT '0009658-8-1','20','2010-5-12 09:20:30','2010-5-13 12:10:00' --SELECT * FROM [tb] --我想得到表A第一行的 "end_time "与第二行的 "start_time "相减的值,第二行的 "end_time "与第三行的 "start_time "相减的值, --第三行的 "end_time "与第四行的 "start_time "相减的值,以此类推,请问怎样实现呢? -->SQL查询如下: ;with t as ( select rn=row_number()over(ORDER by job),* from tb ) select a.*,val=datediff(mi,a.end_time,b.bstart_time) from t a outer apply( select bstart_time=start_time from t where a.rn=rn-1 ) b /* rn job gx_id start_time end_time val -------------------- -------------------- ----------- ----------------------- ----------------------- ----------- 1 0001011-3-1 10 2010-05-10 10:00:0