我想搜索上一次call.group在一小时内拨打的电话。员工和day.And我只想显示在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因为第二次电话是在第一次通话一小时(即使它在不同的时间内掉落)。
答案 0 :(得分: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
答案 1 :(得分:1)
一种方法是添加一个行号列并进行自联接以计算与“第一”行的差异。
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