Hi There,[img]http://www.sqlservercentral.com/Forums/Attachment19679.aspx[/img]I got output but it seems very costly, so looking for some optimal solution.[code="sql"]create table #ME (memid int , EffectiveDate datetime , termdate datetime)Insert into #ME values ('123','3-Dec-16','10-Jan-17')Insert into #ME values ('123','11-Jan-17','6-Feb-17')Insert into #ME values ('123','7-Feb-17','5-Mar-17')Insert into #ME values ('123','8-Mar-17','15-Apr-17')Insert into #ME values ('123','16-Apr-17','24-May-17') declare @StartDate datetime , @CutoffDate datetimeselect @StartDate= min(effectivedate),@CutoffDate = max(termdate) From #me where termdate<>'9999-12-31 00:00:00.000'SELECT d into #dimFROM( SELECT d = DATEADD(DAY, rn - 1, @StartDate) FROM ( SELECT TOP (DATEDIFF(DAY, @StartDate, @CutoffDate)) rn = ROW_NUMBER() OVER (ORDER BY s1.[object_id]) FROM sys.all_objects AS s1 CROSS JOIN sys.all_objects AS s2 -- on my system this would support > 5 million days ORDER BY s1.[object_id] ) AS x) AS y;select MemID, D As DateSpread Into #MemEligibilityDateSpread From #Dim dim JOIN #me ME on dim.d between ME.effectivedate and me.termdate WITH CTE AS ( SELECT MEmID, UniqueDate = DateSpread, DateGroup = DATEADD(dd, - ROW_NUMBER() OVER (PARTITION BY Memid ORDER BY Memid,DateSpread), DateSpread) FROM #MemEligibilityDateSpread GROUP BY Memid,DateSpread)--===== Now, if we find the MIN and MAX date for each DateGroup, we'll have the -- Start and End dates of each group of contiguous daes. While we're at it, -- we can also figure out how many days are in each range of days. SELECT Memid, StartDate = MIN(UniqueDate), EndDate = MAX(UniqueDate) INTO #DateClasified FROM cte -- where MemID= 'H5716216700' GROUP BY Memid,DateGroup ORDER BY Memid,StartDateselect ME.MemID,ME.EffectiveDate,ME.TermDate,DC.StartDate,DC.EndDate from #DateClasified dc join #me ME ON Me.MemID = dc.MemID and (ME.EffectiveDate BETWEEN DC.StartDate AND DC.EndDate OR ME.TermDate BETWEEN DC.StartDate AND DC.EndDate) [/code]Thanks in advance
↧