I\'ve seen a lot of solutions to identify records where date ranges overlap, and still other examples of merging overlapping ranges.
However I am interested in results
Here's the answer:
select t.customerid, t.eff_dt, count(distinct t2.productId),
MIN(t2.end_dt) as end_dt
from #tmp t join
#tmp t2
on t.CustomerID = t2.CustomerID and
t.Eff_Dt between t2.Eff_Dt and t2.End_Dt
group by t.CustomerID, t.eff_dt
having count(distinct t2.productId) = 3
This is using a self-join to count the number of different products on each eff_dt
. You want three distinct products, so that is what the having
clause is doing.
There are three distinct products until one of them ends. That would be the first end_dt
after the effective date -- which is calculated by the min(end_dt)
.