找到序列之间的缺失日期

时间:2013-01-30 05:42:18

标签: sql sql-server tsql

我需要找到12月份之间缺失的差距,并使用SQL查询填补空白

我有以下查询,它需要tweeking因为它仍然不正确这里是我写的

CREATE TABLE #BenfitDim(MemberName varchar(30),Memberkey int,MemberEffectiveDate DATETIME,
    MemberTerminationDate DATETIME)

INSERT INTO #BenfitDim VALUES('tom',231,'2012-11-18','2012-11-23')
INSERT INTO #BenfitDim VALUES('tom',231,'2012-11-24','2012-12-12')
INSERT INTO #BenfitDim VALUES('tom',231,'2013-01-01','2999-12-12')
INSERT INTO #BenfitDim VALUES('jack',344,'2011-06-27','2012-12-07') 
INSERT INTO #BenfitDim VALUES('jack',344,'2012-12-01','2015-12-31')
INSERT INTO #BenfitDim VALUES('nick',243,'2012-12-01','2012-12-07')
INSERT INTO #BenfitDim VALUES('joy',234,'2012-12-08','2012-12-14')
INSERT INTO #BenfitDim VALUES('tim',364,'2012-12-25','2012-12-30')
INSERT INTO #BenfitDim VALUES('tim',364,'2013-01-15','2013-01-30')
INSERT INTO #BenfitDim VALUES('jerry',365,'2011-9-15','2012-12-31')
INSERT INTO #BenfitDim VALUES('jerry',365,'2013-01-15','2013-01-30')
INSERT INTO #BenfitDim VALUES('jerry',365,'2011-01-15','2012-01-30')

SELECT MemberKey,
       MemberName,
       DATEADD(DAY,1,T1.MemberTerminationDate)AS MemberEffectiveDate,
       DATEADD(DAY,-1,D.MemberEffectiveDate)AS MemberTerminationDate
FROM
       #BenfitDim AS T1 CROSS APPLY(
                                SELECT MIN(MemberEffectiveDate)AS MemberEffectiveDate
                                  FROM #BenfitDim AS T
                                  WHERE T.MemberEffectiveDate > T1.MemberEffectiveDate 
                                  AND T.MemberKey = T1.MemberKey)D
 WHERE DATEADD(DAY,1,T1.MemberTerminationDate) <>  D.MemberEffectiveDate

一旦执行,您将找到缺失的序列,但仍然存在轻微问题。我们如何处理表格中“jack”的重叠数据,并将缺失的序列正确。 感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我认为下面的查询可以满足您的需求。对于每个会员记录,它将获得下一个成员资格,其中下一个成员资格不会在第二天开始,并且没有重叠的成员资格。

MINGROUP BY只需要获取下一条记录的日期,而不是所有未来的记录。

SELECT      T1.MemberKey,
            T1.MemberName,
            DATEADD(DAY,1,T1.MemberTerminationDate) AS MemberEffectiveDate,
            MIN(DATEADD(DAY,-1,T2.MemberEffectiveDate)) AS MemberTerminationDate

-- current membership
FROM        #BenfitDim AS T1

-- later membership
INNER JOIN  #BenfitDim AS T2                    
ON          T2.MemberKey = T1.MemberKey         
AND         T2.MemberEffectiveDate > T1.MemberTerminationDate

-- no membership following next day or overlapping
WHERE       NOT EXISTS (
            SELECT  T3.MemberEffectiveDate,
                    T3.MemberTerminationDate
            FROM    #BenfitDim AS T3
            WHERE   T3.Memberkey = T1.Memberkey
            AND     (T3.MemberEffectiveDate = DATEADD(DAY,1,T1.MemberTerminationDate)
            OR      T3.MemberEffectiveDate < T1.MemberEffectiveDate
            AND     T3.MemberTerminationDate > T1.MemberEffectiveDate))

GROUP BY    T1.MemberKey,
            T1.MemberName,
            T1.MemberTerminationDate