我有一张桌子,其结构如下:
Account_No Contact Date
-------------------------
1 2013-10-1
2 2013-9-12
3 2013-10-15
3 2013-8-1
3 2013-8-20
2 2013-10-25
4 2013-9-12
4 2013-10-2我需要搜索表,并返回任何帐户号码,有两个联系日期,是在30天内彼此。一些帐号可能有5或6个联系日期。基本上,我只需要返回所有的完整帐号和记录,这是在30天内彼此之间,而忽略其余的。联系人日期存储为日期数据类型。
例如,第3号帐户将返回2013-8-1和2013-8-20记录,同时第4帐号的这两种记录也会出现,但其他帐号记录和2013-10-15年间的帐号3都不会出现。
我正在使用Server 2008 R2。
谢谢您提前提供帮助!
发布于 2013-10-30 23:49:27
您可以将DATEADD用于+/-30天,并与时间窗口进行比较:
DECLARE @ContactDates TABLE (
Account_No int
, Contact Date
)
-- Sample data
INSERT @ContactDates (Account_No, Contact)
VALUES
(1, '2013-10-01')
, (2, '2013-09-12')
, (3, '2013-10-15')
, (3, '2013-08-01')
, (3, '2013-08-20')
, (2, '2013-10-25')
, (4, '2013-09-12')
, (4, '2013-10-02')
-- Find the records within +/-30 days
SELECT c1.Account_No, c1.Contact AS Contact_Date1
FROM @ContactDates AS c1
JOIN (
-- Inner query with the time window
SELECT Account_No
, Contact
, DATEADD(dd, 30, Contact) AS Date_Max
, DATEADD(dd, -30, Contact) AS Date_Min
FROM @ContactDates
) AS c2
-- Compare based on account number, exclude the same date
-- from comparing against itself. Usually this would be
-- a primary key, but this example doesn't show a PK.
ON (c1.Account_No = c2.Account_No AND c1.Contact != c2.Contact)
-- Compare against the +/-30 day window
WHERE c1.Contact BETWEEN c2.Date_Min AND c2.Date_Max这将返回以下内容:
Account_No Contact
========== ==========
3 2013-08-20
3 2013-08-01
4 2013-10-02
4 2013-09-12发布于 2013-10-30 23:30:08
在Server 2012中,您将拥有lag()和lead()函数。在2008年,您可以对同一日历月中的值执行以下操作:
select distinct account_no
from t t1
where exists (select 1
from t t2
where t1.account_no = t2.account_no and
datediff(month, t1.ContactDate, t2.ContactDate) = 0
)在定义一个“月”是什么时候,日期是在不同的月份,有一个小的挑战。(3月16日是2月15日之后的一个月吗?)他们的时间比1月1日和1月31日更近。)你只需要30天就可以了
select distinct account_no
from t t1
where exists (select 1
from t t2
where t1.account_no = t2.account_no and
datediff(day, t1.ContactDate, t2.ContactDate) <= 30
)发布于 2013-10-31 00:06:44
这些记录中的每一个都有身份证吗?如果是这样的话,你就不需要像我一样创建一个,而是基于你发布的数据
With cte as
(
Select *,
row_number() over (order by contact_date) id
From tbl
)
Select *
From cte b
Where exists (
Select 1
From cte a
Where a.account_no = b.account_no
And a.id <> b.id
And a.contact_date between b.contact_date and dateadd(d, 30, b.contact_date)
)https://stackoverflow.com/questions/19695646
复制相似问题