![](/img/trans.png)
[英]T-SQL to find multiple orders from same customer on same day within given date range
[英]t-sql to find repeated callers in customer care
我遇到的情況是,我需要在當月的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
在這里,我需要捕獲他在15日和16日呼叫的號碼0987654321(減少2天的間隔)。 其余號碼0123456789和0789386834將不會包含在結果中,因為他們沒有在2天內撥打電話。 我正在嘗試使用CTE,但它表示內存異常。
PS:它有超過200萬條記錄。
通過此查詢,我得到了預期的結果:
-- 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.