0

我正在使用以下查询来获取 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 纸,如果没有,则忽略。请帮助

4

1 回答 1

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'
于 2013-03-29T12:33:31.000 回答