检查日期在3个月内重叠

时间:2015-02-06 01:38:23

标签: sql sql-server-2008 tsql

我有一张表格如下:

Cola    REF     RecordNumber    StartDate               EndDate             
NAME1   REF001  RECORD011       12/11/2012              11/01/2013     
NAME1   REF001  RECORD012       24/01/2013              10/04/2013  
NAME1   REF001  RECORD013       26/04/2013               9/07/2013     
NAME1   REF001  RECORD014       12/06/2013               2/07/2013  
NAME1   REF001  RECORD015       11/07/2013              17/07/2013      
NAME1   REF001  RECORD016       2/09/2013               23/09/2013   
NAME1   REF001  RECORD017       26/04/2013              6/09/2013      

我需要返回任何行:

  • 可乐是一样的
  • ref是相同的
  • 开始日期或结束日期在任何其他日期的3个月内 记录编号 - 所以也包括任何重叠

到目前为止,我有这个,我相信排除前2:

SELECT DISTINCT Cola
              , Ref
              , RecordNumber
              , StartDate
              , EndDate
FROM datatable a
WHERE EXISTS 
    (
    SELECT TOP 1 1 
    FROM datatable b 
    WHERE b.cola = a.cola 
            AND b.ref = a.ref 
            AND b.id <> a.id)

我在日期检查部分苦苦挣扎,有人能指出我正确的方向吗?

我想我最终应该

Cola    REF     RecordNumber    StartDate               EndDate             
NAME1   REF001  RECORD011       12/11/2012              11/01/2013         
NAME1   REF001  RECORD014       12/06/2013               2/07/2013       
NAME1   REF001  RECORD017       26/04/2013               6/09/2013     

1 个答案:

答案 0 :(得分:2)

您需要在子查询中添加日期算术。这是一个例子:

SELECT dt.*
FROM datatable dt
WHERE EXISTS (SELECT 1 
              FROM datatable dt2 
              WHERE dt2.cola = dt.cola AND
                    dt2.ref = dt.ref AND
                    dt2.id <> dt.id AND
                    (dt.startdate between dateadd(month, -3, dt2.startdate) and
                                          dateadd(month, 3, dt2.enddate) or
                     dt.enddate between dateadd(month, -3, dt2.startdate) and
                                        dateadd(month, 3, dt2.enddate)
                    )
             );