如何使用sql select query获取所有记录中两个日期之间的差异

时间:2015-11-26 04:17:34

标签: sql-server datetime

让我解释一下我想要的东西: 假设我的表中有100条记录(列名:id,imei,纬度,经度,日期时间,状态)

然后,我放了50条记录,10000001 imei号码,现在我必须得到状态为0且日期差异超过5分钟的记录与同一个imei。

如何获取状态为0且持续时间超过5的记录?

在排序中,我需要比较1个日期和2个日期,然后是2个日期和3个日期,然后是3个日期和4个日期,然后是4个日期和5个日期,依此类推。

1 个答案:

答案 0 :(得分:0)

这将对imei进行分组并按日期时间对它们进行排序,然后按照升序对每个日期时间进行比较。既然你没有给出更好的方法来排序它们,我会假设这就是你要找的东西

; WITH T AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY imei ORDER BY datetime) RN
    FROM tblName)
SELECT T1.imei, T1.status, T1.datetime [date1], T2.datetime [date2], DATEDIFF(mi, T1.datetime, T2.datetime) [difference]
FROM T T1 
JOIN (SELECT imei, RN, datetime FROM T WHERE RN > 1) T2 ON T2.RN-1 = T1.RN AND T1.imei = T2.imei
WHERE T1.datetime < DATEADD(mm, -5, T2.datetime)
AND T1.Status = 0

或者,如果您只想要日期差异(无论它们是否大于或小于5),您可以这样做:

; WITH T AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY imei ORDER BY datetime) RN
    FROM tblName)
SELECT T1.imei, T1.status, T1.datetime [date1], T2.datetime [date2], DATEDIFF(mi, T1.datetime, T2.datetime) [difference], CASE WHEN DATEDIFF(mi, T1.datetime, T2.datetime) > 5 THEN 'Y' ELSE 'N' END -- 'Y' means greater than 5, 'N' less than or equal to 5
FROM T T1 
LEFT JOIN (SELECT imei, RN, datetime FROM T WHERE RN > 1) T2 ON T2.RN-1 = T1.RN AND T1.imei = T2.imei
WHERE T1.Status = 0