如何查找具有最接近日期时间值的两个记录之间的日期差异,并且必须在同一组中进行比较?
示例数据如下:
Select * from tblGroup
Group FinishedDatetime 1 03-01-2009 00:00 1 13-01-2009 22:00 1 08-01-2009 03:00 2 01-01-2009 10:00 2 13-01-2009 20:00 2 10:01-2009 10:00 3 27-10-2008 00:00 3 29-10-2008 00:00
预期产出:
Group FinishedDatetime Hours 1 03-01-2009 00:00 123 1 13-01-2009 22:00 139 1 08-01-2009 03:00 117 2 01-01-2009 10:00 216 2 13-01-2009 20:00 82 2 10:01-2009 10:00 82 3 27-10-2008 00:00 48 3 29-10-2008 00:00 48
答案 0 :(得分:1)
试试这个:
Select t1.[Group], DATEDIFF(HOUR, z.FinishedDatetime, t1.FinishedDatetime)
FROM tblGroup t1
OUTER APPLY(SELECT TOP 1 *
FROM tblGroup t2
WHERE t2.[Group] = t1.[Group] AND t2.FinishedDatetime<t1.FinishedDatetime
ORDER BY FinishedDatetime DESC)z