1+ /* ********************************************************************
2+ Scott Peters
3+ Merge Overlapping Records
4+ https://advancedsqlpuzzles.com
5+ Last Updated: 07/25/2022
6+
7+ This script is written in SQL Server's T-SQL
8+
9+ ---------------------------------------------------------------------
10+
11+ Script merges overlapping records
12+ I have broken the script into multiple steps to aid in understanding
13+
14+ **********************************************************************/
15+ -- -------------------
16+ -- -------------------
17+ -- Tables used in script
18+ DROP TABLE IF EXISTS #Numbers;
19+ DROP TABLE IF EXISTS #Distinct_StartIntegers;
20+ DROP TABLE IF EXISTS #OuterJoin;
21+ DROP TABLE IF EXISTS #DetermineValidEndIntegers;
22+ DROP TABLE IF EXISTS #DetermineValidEndIntegers2;
23+ GO
24+
25+ -- -------------------
26+ -- -------------------
27+ -- Create and populate #Numbers table
28+ CREATE TABLE #Numbers
29+ (
30+ StartInteger INTEGER ,
31+ EndInteger INTEGER
32+ );
33+ GO
34+
35+ INSERT INTO #Numbers VALUES
36+ (1 ,5 ),
37+ (1 ,3 ),
38+ (1 ,2 ),
39+ (3 ,9 ),
40+ (10 ,11 ),
41+ (12 ,16 ),
42+ (15 ,19 );
43+ GO
44+
45+ -- -------------------
46+ -- -------------------
47+ -- Create and populate #Distinct_StartIntegers table
48+ -- Step 1
49+ SELECT DISTINCT
50+ StartInteger
51+ INTO #Distinct_StartIntegers
52+ FROM #Numbers;
53+ GO
54+
55+ -- -------------------
56+ -- -------------------
57+ -- Create and populate #OuterJoin table
58+ -- Step 2
59+ SELECT a .StartInteger AS StartInteger_A,
60+ a .EndInteger AS EndInteger_A,
61+ b .StartInteger AS StartInteger_B,
62+ b .EndInteger AS EndInteger_B
63+ INTO #OuterJoin
64+ FROM #Numbers AS a LEFT OUTER JOIN
65+ #Numbers AS b ON a .EndInteger >= b .StartInteger AND
66+ a .EndInteger < b .EndInteger ;
67+ GO
68+
69+ -- -------------------
70+ -- -------------------
71+ -- Create and populate #DetermineValidEndIntegers table
72+ -- Step 3
73+ SELECT EndInteger_A
74+ INTO #DetermineValidEndIntegers
75+ FROM #OuterJoin
76+ WHERE StartInteger_B IS NULL
77+ GROUP BY EndInteger_A;
78+ GO
79+
80+ -- -------------------
81+ -- -------------------
82+ -- Create and populate #DetermineValidEndIntegers2 table
83+ -- Step 4
84+ SELECT a .StartInteger , MIN (b .EndInteger_A ) AS MinEndInteger_A
85+ INTO #DetermineValidEndIntegers2
86+ FROM #Distinct_StartIntegers a INNER JOIN
87+ #DetermineValidEndIntegers b ON a .StartInteger <= b .EndInteger_A
88+ GROUP BY a .StartInteger
89+ GO
90+
91+ -- -------------------
92+ -- -------------------
93+ -- Display the results
94+ -- Step 5
95+ SELECT MIN (StartInteger) AS StartInteger,
96+ MAX (MinEndInteger_A) AS EndInteger
97+ FROM #DetermineValidEndIntegers2
98+ GROUP BY MinEndInteger_A;
99+ GO
0 commit comments