1

我需要找到 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”的重叠数据并正确获取缺失的序列。感谢您的帮助。

4

1 回答 1

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
于 2013-01-30T11:03:15.727 回答