我有这样的情况,我需要在当前月份的2天内找出在同一号码内拨打客户服务的号码。例如:
Number dateTime
0987654321 2015-06-16 16:16:13.877
0987654321 2015-06-15 12:16:13.877
0789386834 2015-06-01 16:16:13.877
0789386834 2015-06-16 16:16:13.877
0987654321 2015-06-01 12:16:13.877
0123456789 2015-06-01 12:16:13.877
0123456789 2015-06-06 12:16:13.877
0123456789 2015-06-16 12:16:13.877
在这里,我需要捕捉号码0987654321,因为他在15号和16号(较少2天的差距)进行了调用。休息,0123456789和0789386834将不会包含在结果中,因为他们的电话未在2天内完成。我正在尝试使用CTE,但它说存在异常。
PS:它有超过200万条记录。
答案 0 :(得分:1)
我通过此查询得到了预期的结果:
-- dummy table
DECLARE @tab TABLE
(
number VARCHAR(100),
timeofcall DATETIME
)
--insert sample values
INSERT INTO @tab
VALUES
('0987654321','2015-06-16 16:16:13.877'),
('0987654321','2015-06-15 12:16:13.877'),
('0789386834','2015-06-01 16:16:13.877'),
('0789386834','2015-06-16 16:16:13.877'),
('0987654321','2015-06-01 12:16:13.877'),
('0123456789','2015-06-01 12:16:13.877'),
('0123456789','2015-06-06 12:16:13.877'),
('0123456789','2015-06-16 12:16:13.877')
--get records who are present in the table within 2 days
SELECT *
FROM @tab t
WHERE EXISTS(SELECT TOP 1 1
FROM @tab t2
WHERE t2.number = t.number
AND t2.timeofcall <> t.timeofcall
AND ABS(DATEDIFF(DAY,t2.timeofcall,t.timeofcall)) <= 2)