sql-server-2005根据日期查询连续3天的第2条记录

时间:2015-11-04 17:52:18

标签: sql-server-2005

我需要连续3天为每位有事件(访问建筑物)的员工提取第二条记录,并且只为每位员工提供最早的结果。

时间没有考虑在内。

我的表格如下:

EMPID   EVENTIME
4   2015-08-05 13:34:54.000
4   2015-08-19 16:29:32.000
4   2015-08-21 16:30:35.000
4   2015-08-24 13:51:25.000
4   2015-08-24 16:32:39.000
4   2015-08-26 13:48:32.000
4   2015-08-26 16:29:58.000
4   2015-08-27 16:30:07.000
4   2015-08-28 14:00:02.000
4   2015-08-28 16:29:09.000
19  2015-08-10 07:27:10.000
19  2015-08-10 15:18:51.000
19  2015-08-11 07:33:12.000
19  2015-08-11 07:33:16.000
19  2015-08-11 10:19:56.000
19  2015-08-11 15:49:12.000
19  2015-08-12 07:21:06.000
19  2015-08-12 10:37:53.000
19  2015-08-12 12:48:12.000
19  2015-08-12 14:11:25.000
19  2015-08-12 15:01:18.000
19  2015-08-13 07:25:38.000
21  2015-08-03 10:07:00.000
21  2015-08-10 08:00:41.000

期望的结果如下:

EMPID   EVENTIME
4   2015-08-27 //first record that had an event 1 day before and 1 day after
19  2015-08-11 //first record that had an event 1 day before and 1 day after

由于访问权限由感应卡控制,并且这些都经过测试,然后几天后交付给新员工,那么第一个记录将无效,并且连续3天的第一个记录也将无效卡从早上下午发送。这就是为什么我需要查询前连续3天的第二条记录。

这将为我提供可用于报告的每位员工的开始日期。

我正在使用mssql 2005。

谢谢!

1 个答案:

答案 0 :(得分:0)

经过几个小时的挣扎,我终于做到了。如果有人需要它:

WITH RESULTS AS(
    SELECT EVENTS.EMPID, CAST(DATEDIFF(d,0,EVENTS.EVENTIME) AS DATETIME) AS EVENTIME, COUNT(CAST(DATEDIFF(d,0,EVENTS.EVENTIME) AS DATETIME)) AS THIS_DAY
    FROM EVENTS INNER JOIN EMP ON EVENTS.EMPID = EMP.ID
    WHERE (EVENTIME > '2015-08-01')
    GROUP BY EVENTS.EMPID, CAST(DATEDIFF(d,0,EVENTS.EVENTIME) AS DATETIME)
)
SELECT A.EMPID, MIN(A.EVENTIME) AS EVENTIME
FROM RESULTS A
    INNER JOIN RESULTS B ON A.EMPID = B.EMPID
    AND CAST(DATEDIFF(d,0,B.EVENTIME) AS DATETIME) = CAST(DATEDIFF(d,0,DATEADD(d,-1,A.EVENTIME)) AS DATETIME)
    INNER JOIN RESULTS C ON B.EMPID = C.EMPID
    AND CAST(DATEDIFF(d,0,C.EVENTIME) AS DATETIME) = CAST(DATEDIFF(d,0,DATEADD(d,1,A.EVENTIME)) AS DATETIME)
GROUP BY A.EMPID
ORDER BY A.EMPID