2

我想按员工和日期搜索上一次通话后一小时内拨打的电话。我只想显示在 1 小时间隔内只拨打一次电话的行。

样本数据:

day          calltime                  emplno  empname
2013-11-13   2013-11-13 18:38:39.347   1       James Johnson
2013-11-12   2013-11-12 18:39:57.570   2       Steve Thomson
2013-11-12   2013-11-12 19:05:01.027   2       Steve Thomson
2013-11-12   2013-11-12 15:38:11.853   2       Steve Thomson
2013-11-12  2013-11-12 19:20:01.027    2       Steve Thomson
2013-11-12  2013-11-12 19:45:46.357    2       Steve Thomson
2013-11-12   2013-11-12 18:40:11.853   1       James Johnson

我想要这样的结果:

day          calltime                  emplno  empname
2013-11-13   2013-11-13 18:38:39.347   1       James Johnson
2013-11-12  2013-11-12 19:45:46.357    2       Steve Thomson
2013-11-12   2013-11-12 15:38:11.853   2       Steve Thomson
2013-11-12   2013-11-12 18:40:11.853   1       James Johnson

我不想显示电话 2013-11-12 18:39:57.570, 2013-11-12 19:05:01.027 和 2013-11-12 19:20:01.027 因为第二个电话发生在一小时内第一个电话(即使它在不同的小时内落下)。

4

2 回答 2

2
DECLARE @x TABLE([day] DATE, calltime DATETIME, emplno INT, empname VARCHAR(32));

INSERT @x VALUES
('2013-11-13','2013-11-13 18:38:39.347',1,'James Johnson'),
('2013-11-12','2013-11-12 18:39:57.570',2,'Steve Thomson'),
('2013-11-12','2013-11-12 19:05:01.027',2,'Steve Thomson'),
('2013-11-12','2013-11-12 15:38:11.853',2,'Steve Thomson'),
('2013-11-12','2013-11-12 18:40:11.853',1,'James Johnson');


;WITH x AS 
(
  SELECT x.emplno, x.empname, c1 = x.calltime, c2 = x2.calltime 
  FROM @x AS x INNER JOIN @x AS x2 ON x2.emplno = x.emplno 
  AND x2.calltime > x.calltime AND x2.calltime < DATEADD(HOUR, 1, x.calltime)
),
y AS 
(
  SELECT x.emplno, x.empname, x.c1 FROM x
  UNION SELECT x.emplno, x.empname, x.c2 FROM x
)
SELECT [day] = CONVERT(DATE, calltime), calltime, emplno, empname FROM @x
EXCEPT SELECT CONVERT(DATE, c1), c1, emplno, empname FROM y;

结果:

day         calltime                 emplno  empname
----------  -----------------------  ------  -------------
2013-11-12  2013-11-12 15:38:11.853  2       Steve Thomson
2013-11-12  2013-11-12 18:40:11.853  1       James Johnson
2013-11-13  2013-11-13 18:38:39.347  1       James Johnson
于 2013-11-13T19:19:38.620 回答
1

One way is to add a Row Number column and do a self-join to compute the difference to the "first" row.

WITH Calls AS
(
    SELECT 
        day, 
        calltime, 
        emplno, 
        empname,
        ROW_NUMBER() OVER (PARTITION BY emplno ORDER BY calltime) RowNum
  FROM CallLog

)
SELECT C1.*
FROM Calls C1
INNER JOIN Calls C2 
  ON C1.EmplNo = c2.EmplNO
     AND C2.RowNum = 1
WHERE DATEDIFF(minute,C2.CallTime, C1.CAllTime) <= 60
于 2013-11-13T19:27:26.417 回答