我正在使用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
希望有人可以帮助我!谢谢你!
答案 0 :(得分:1)
您可以将相关子查询与CASE
和DATEDIFF
:
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