I need a solution for merging date periods in SQL Server.
The below sets up the working example. I have two tables, the first holding a single period for a particular product, the second holding smaller periods that fall within the related period from the first table. I need to merge the two so that I end up with a list of all the contiguous periods covering the original period when including the smaller periods. I’ve included a sample of the desired result.
Rules:
- There would only ever be a single row in the first table per product
- The rows in the second table would never overlap for a product
- The rows in the second table would only ever fall on or within the boundaries of the original period
declare @x table (product varchar(10), fromdate date, todate date) -- forecast
declare @y table (product varchar(10), fromdate date, todate date) -- purchases
declare @z table (product varchar(10), fromdate date, todate date) -- result
insert @x values ('lrecs', '20150101', '20161231')
insert @x values ('srecs', '20150701', '20161231')
insert @y values ('lrecs', '20150401', '20150630')
insert @y values ('lrecs', '20160101', '20160630')
insert @y values ('srecs', '20160101', '20161231')
/*
product fromdate todate
------------------------------
lrecs 2015-01-01 2015-03-31
lrecs 2015-04-01 2015-06-30
lrecs 2015-07-01 2015-12-31
lrecs 2016-01-01 2016-06-30
lrecs 2016-07-01 2016-12-31
srecs 2015-07-01 2015-12-31
srecs 2016-01-01 2016-12-31
*/
WHILEloop is still aCURSOR. See this article for details. - Felix PamittanLEADandLAGfunctions that help to solve this "gaps and islands" problem efficiently. - Vladimir Baranov