日付範囲が重複するレコードを特定するための多くのソリューションや、重複する範囲をマージする他の例を見てきました。
ただし、オーバーラップのみが発生する範囲を示す結果に興味があります。実際、私は3つのProductIDを持っており(そして3つだけが存在することになります)、顧客が3つすべてを持っていたときの各顧客の日付範囲を見つけようとしています。
SET NOCOUNT ON;
CREATE TABLE #tmp
(
CustomerID integer
,ProductID varchar(12)
,Eff_Dt DATE
,End_Dt DATE
);
-- Customer 1000: Expecting results to show 2 rows: 1/1 - 1/5 and 1/10 - 1/15
INSERT INTO #tmp VALUES (1000,'PRODUCT_A','01-01-2013' ,'01-31-2013' );
INSERT INTO #tmp VALUES (1000,'PRODUCT_B','01-01-2013' ,'01-05-2013' );
INSERT INTO #tmp VALUES (1000,'PRODUCT_B','01-10-2013' ,'01-15-2013' );
INSERT INTO #tmp VALUES (1000,'PRODUCT_C','01-01-2013' ,'01-31-2013' );
-- Customer 2000: Expecting results to show 1 row: 1/19 - 1/31
INSERT INTO #tmp VALUES (2000,'PRODUCT_A','01-01-2013' ,'01-31-2013' );
INSERT INTO #tmp VALUES (2000,'PRODUCT_B','01-01-2013' ,'01-31-2013' );
INSERT INTO #tmp VALUES (2000,'PRODUCT_C','01-19-2013' ,'01-31-2013' );
-- Customer 3000: Expecting results to show no rows (or nulls)
INSERT INTO #tmp VALUES (3000,'PRODUCT_A','01-01-2013' ,'01-10-2013' );
INSERT INTO #tmp VALUES (3000,'PRODUCT_A','01-16-2013' ,'01-31-2013' );
INSERT INTO #tmp VALUES (3000,'PRODUCT_B','01-01-2013' ,'01-12-2013' );
INSERT INTO #tmp VALUES (3000,'PRODUCT_C','01-15-2013' ,'01-31-2013' );
-- Customer 4000: Expecting results to show 1 row: 1/15 - 1/23
INSERT INTO #tmp VALUES (4000,'PRODUCT_A','01-15-2013' ,'01-31-2013' );
INSERT INTO #tmp VALUES (4000,'PRODUCT_B','01-01-2013' ,'01-31-2013' );
INSERT INTO #tmp VALUES (4000,'PRODUCT_C','01-01-2013' ,'01-23-2013' );
-- Customer 5000: Expecting results to show 0 rows
INSERT INTO #tmp VALUES (5000,'PRODUCT_A','01-17-2013' ,'01-31-2013' );
INSERT INTO #tmp VALUES (5000,'PRODUCT_B','01-01-2013' ,'01-10-2013' );
INSERT INTO #tmp VALUES (5000,'PRODUCT_C','01-07-2013' ,'01-19-2013' );
-- Customer 6000: Expecting results to show 3 rows: 1/11 - 1/12 1/17 - 1/22 1/26 - 1/27
INSERT INTO #tmp VALUES (6000,'PRODUCT_A','01-01-2013' ,'01-04-2013' );
INSERT INTO #tmp VALUES (6000,'PRODUCT_A','01-09-2013' ,'01-12-2013' );
INSERT INTO #tmp VALUES (6000,'PRODUCT_A','01-17-2013' ,'01-22-2013' );
INSERT INTO #tmp VALUES (6000,'PRODUCT_A','01-26-2013' ,'01-31-2013' );
INSERT INTO #tmp VALUES (6000,'PRODUCT_B','01-04-2013' ,'01-28-2013' );
INSERT INTO #tmp VALUES (6000,'PRODUCT_C','01-11-2013' ,'01-27-2013' );
SET NOCOUNT OFF;
/* ====== EXPECTED RESULTS =======================
CustomerID EFF_DT END_DT
1000 1/1/2013 1/5/2013
1000 1/10/2013 1/15/2013
2000 1/19/2013 1/31/2013
4000 1/15/2013 1/23/2013
6000 1/11/2013 1/12/2013
6000 1/17/2013 1/22/2013
6000 1/26/2013 1/27/2013
===================================================*/