T-SQL– Find Gap and Island for Date Range
Posted: August 21, 2014 Filed under: Uncategorized 2 CommentsHere is a solution for gaps and island from Alejandro Mesa:
Another one:
SET NOCOUNT ON; USE tempdb; GO create table #test (Item char(1), [Date] Date) GO Insert into #test VALUES ('A', '8/21/2014'),('A', '8/22/2014'),('A', '8/25/2014'), ('B', '09/12/2014'),('B', '09/13/2014'),('B', '09/14/2014'), ('A', '10/11/2014'),('A', '10/12/2014'),('A', '10/13/2014') GO ;with mycte as ( SELECT *, DATEADD(DAY, - ROW_NUMBER() OVER(PARTITION BY Item ORDER BY [Date]), [Date]) AS grp FROM #test ) select Item, min([Date]) as[From],max([Date]) as [To] from mycte group by Item, grp Order by Item, grp GO drop table #test GO
Thanks for the SQL query. This was exactly what I was looking for.
[…] are not consecutive, then you have what is known as a ‘Gaps and Island’ problem. I took this example and tweaked it for your situation. I added a new row for code ‘F’ with a date of […]