Overlapping Date Ranges - Identifying Only the Overlap

后端 未结 3 615
我寻月下人不归
我寻月下人不归 2021-01-27 00:23

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

3条回答
  •  面向向阳花
    2021-01-27 00:40

    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).

提交回复
热议问题