如何比较行值和下一行之间的日期列

时间:2016-01-14 13:28:26

标签: sql sql-server sql-server-2008 tsql

我正在使用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

我想选择另一个布尔列,如果前一行比“父亲”行少1分钟,则返回true,如下例所示:

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
希望有人可以帮助我!谢谢你!

1 个答案:

答案 0 :(得分: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