2016-01-14 93 views
0

我正在使用SQL Server 2008 R2。我有一個表沒有ID列如下:如何比較行值和下一行之間的日期列

2016-01-14 11:14:00.000 
2016-01-14 11:13:00.000 
2016-01-14 11:12:00.000 
2016-01-14 11:11:00.000 
2016-01-14 11:10:00.000 
2016-01-14 11:09:00.000 
2016-01-14 11:08:00.000 
2016-01-14 11:07:00.000 

我想多一個布爾列誰返回true,如果上一行以1分不到你的「父親」行,像下面選擇此例如:

2016-01-14 11:14:00.000 | true 
2016-01-14 11:13:00.000 | true 
2016-01-14 11:12:00.000 | false (because the previous row is 2 minutes less) 
2016-01-14 11:10:00.000 | true 
2016-01-14 11:09:00.000 | true 
2016-01-14 11:08:00.000 | false (because the previous row is 3 minutes less) 
2016-01-14 11:05:00.000 

希望有人能幫助我!現在感謝!

+0

你如何確定_previous row_,由'datetime'值排序? –

+0

我通過desc列排序日期 –

+0

@tim schmelter:我認爲它很好,以upvote接受的答案作爲表示讚賞的努力 – TheGameiswar

回答

1

您可以使用相關子查詢與CASEDATEDIFF

SELECT DateColumn, 
     IsPrevOneMinuteLess = 
     CASE WHEN DATEDIFF(minute, 
         (SELECT MAX(DateColumn) 
          FROM dbo.TableName t2 
          WHERE t2.DateColumn < t.DateColumn), 
          DateColumn) = 1 
     THEN 'true' ELSE 'false' END      
FROM dbo.TableName t 
+0

完美!
剛剛在「SELECT MAX(DateColumn) FROM dbo.TableName t2 WHERE t2.DateColumn 非常感謝! –