使用日期条件从表中提取数据

时间:2013-10-05 11:29:13

标签: sql sql-server-2000

表1:

PHONE_NUMBER | DATE
--------------------------    
   10005     | 5/10/2013
   15555     | 7/17/2013
   58746     | 9/20/2013

表2:

PHONE_NUMBER | DATE
--------------------------    
   10005    | 5/12/2013
   10005    | 5/16/2013
   15555    | 6/17/2013
   15555    | 7/19/2013
   58746    | 8/22/2013
   58746    | 12/26/2013
   58746    | 9/20/2013

从上面的两个表中,我想通过将表1的电话号码与表2的电话号码相对应来从表2中提取数据,表2中的日期可以完全相同的日期或相应的电话号码日期的+/- 5天。表1的。

表2将有重复的语音,并且应提取符合上述条件的所有重复项。

2 个答案:

答案 0 :(得分:3)

如果我理解你的问题,这应符合要求:

SELECT
        t2.phone_number
      , convert(varchar(10),t2.[date],121) as t2_date
      , convert(varchar(10),t1.[date],121) as t1_date
      , datediff(DAY,t1.[date], t2.[date]) as diff_dates
FROM table2 AS t2
INNER JOIN table1 AS t1 ON t2.phone_number = t1.phone_number
                       AND t2.[date] between dateadd(day,-5,t1.[date]) and dateadd(day,5,t1.[date])

请参阅:this sqlfiddle

样本数据的结果:

| PHONE_NUMBER |    T2_DATE |    T1_DATE | DIFF_DATES |
|--------------|------------|------------|------------|
|        10005 | 2013-05-12 | 2013-05-10 |          2 |
|        15555 | 2013-07-19 | 2013-07-17 |          2 |
|        58746 | 2013-09-20 | 2013-09-20 |          0 |

答案 1 :(得分:2)

/ *假设您的日期字段是有效的日期数据类型* /

SELECT a.* FROM TABLE1 a INNER JOIN TABLE2 b 
ON a.phone=b.phone AND (a.[date]=b.[date] OR b.[date] BETWEEN DATEADD(day,-5,b.[date]) AND DATEADD(day,5,b.[date]))