sql中的日期差异

时间:2013-03-29 12:00:52

标签: sql sql-server datetime

我使用以下查询来获得2个时间记录之间的时差

;WITH x AS 
(
  SELECT *, 
    rn = ROW_NUMBER() OVER (PARTITION BY PersonRFID ORDER BY TimeStamp)
  FROM AISDb
)
SELECT y.ID,x.ID,x.PersonName,x.PersonRFID, DATEDIFF(MINUTE, x.TimeStamp, y.TimeStamp) 
  FROM x INNER JOIN x AS y 
  ON x.PersonRFID = y.PersonRFID
  AND x.rn = y.rn - 1
  WHERE x.Action = 'OUT'
  AND y.Action = 'IN';
ID   Name         PERSONRFID                   ACTION  LOGREAD  TIMESTAMP      DATESTAMP

1  Kashif Islam E20010018303014826000F5A    IN  True    20:43:00    1/16/2013

8  Kashif Islam E20010018303014826000F5A    IN  True    12:22:00    1/26/2013

10 Kashif Islam E20010018303014826000F5A    OUT True    12:22:00    1/26/2013

11 Aamir Munir  E20010018303020025901029    IN  True    12:22:00    1/26/2013

15 Aamir Munir  E20010018303020025901029    OUT True    11:46:00    1/29/2013

25 Kashif Islam E20010018303014826000F5A    OUT True    12:41:00    1/29/2013

问题是我在同一天制作IN OUT对的同一天得到了很好的结果。但是如果它没有在同一天找到下一个OUT,例如在2013年1月16日ID为1的情况下,它不会获得OUT操作,因此它与ID 25成对。这不应该做。所以简而言之,我需要查询来处理日期,并使IN OUT文件的日期相同,如果没有则忽略。帮助

1 个答案:

答案 0 :(得分:0)

您只需要在日期添加比较:

WITH x AS 
(
  SELECT *, 
    rn = ROW_NUMBER() OVER (PARTITION BY PersonRFID ORDER BY TimeStamp)
  FROM AISDb
)
SELECT y.ID,x.ID,x.PersonName,x.PersonRFID, DATEDIFF(MINUTE, x.TimeStamp, y.TimeStamp) 
FROM x INNER JOIN
      x AS y 
     ON x.PersonRFID = y.PersonRFID and
        x.rn = y.rn - 1 and
        x.Action = 'OUT' and
        y.Action = 'IN' and
        cast(x.timestamp as date) = cast(y.timestamp as date);

我正在使用SQL Server语法进行到目前为止的转换。

如果你想要所有'X'记录,即使没有匹配的Y,你需要一个左外连接。我会把查询写成:

SELECT y.ID,x.ID,x.PersonName,x.PersonRFID, DATEDIFF(MINUTE, x.TimeStamp, y.TimeStamp) 
FROM x INNER JOIN
      x AS y 
     ON x.PersonRFID = y.PersonRFID and
        x.rn = y.rn - 1 and
        y.Action = 'IN' and
        cast(x.timestamp as date) = cast(y.timestamp as date);
where x.Action = 'OUT'