第一个记录的结束日期与下一个记录的第一个日期之间的时差

时间:2011-08-05 06:06:06

标签: sql tsql sql-server-2008

如何在不同列级别之间找到以分钟为单位的日期差异

No SourceID  RecordID  Start Date               End Date
1  1         1         2009-09-07 09:12:00.0000 2009-09-07 11:00:00.0000 
2  1         1         2009-09-07 11:19:00.0000 2009-09-07 12:12:00.0000  
3  1         1         2009-09-07 12:23:00.0000 2009-09-07 12:54:00.0000  
4  1         1         2009-09-07 13:49:00.0000 2009-09-07 14:45:00.0000 

如何区分第一条记录的EndDate与下一条记录的开始日期和最后一条具有NULL值的记录。

这里 结果需要得到

 SourceID  RecordID  Start Date               End Date                 DiffMin
 1         1         2009-09-07 09:12:00.0000 2009-09-07 11:00:00.0000 19 
 1         1         2009-09-07 11:19:00.0000 2009-09-07 12:12:00.0000 11 
 1         1         2009-09-07 12:23:00.0000 2009-09-07 12:54:00.0000 55 
 1         1         2009-09-07 13:49:00.0000 2009-09-07 14:45:00.0000 NULL

由于

Prav

2 个答案:

答案 0 :(得分:4)

SELECT  SourceId,RecordId,StartDate,EndDate
   , DATEDIFF(mi,a.EndDate,b.StartDate) DiffMin
FROM table a
LEFT JOIN table b ON A.no = B.no+1

答案 1 :(得分:0)

SELECT SourceId,
       RecordId,
       StartDate,
       EndDate,
       DATEDIFF(mi,a.EndDate,b.StartDate) DiffMin
FROM table a
LEFT JOIN table b ON A.no = B.no-1