Numbering islands in SQL Server 2012

Przemyslaw Wojda

I need to number islands in SQL Server 2012. Island is defined as a set of rows where there is no day gaps between DateFrom and DateTo within the same ItemId).

The following dataset:

CREATE TABLE #Ranges (ItemId INT, DateFrom DATETIME, DateTo DATETIME)

INSERT INTO #Ranges VALUES (1,'2015-01-31','2015-02-17')
INSERT INTO #Ranges VALUES (1,'2015-02-18','2015-03-31')
INSERT INTO #Ranges VALUES (1,'2015-04-14','2015-05-21')
INSERT INTO #Ranges VALUES (2,'2015-07-12','2015-07-19')
INSERT INTO #Ranges VALUES (2,'2015-07-20','2015-07-24')
INSERT INTO #Ranges VALUES (2,'2015-07-26','2015-08-02')
INSERT INTO #Ranges VALUES (2,'2015-08-03','2015-08-07')

should be numbered as following:

ItemId;  DateFrom;    DateTo;      Number
1;       2015-01-31;  2015-02-17;  1
1;       2015-02-18;  2015-03-31;  1
1;       2015-04-14;  2015-05-21;  2
2;       2015-07-12;  2015-07-19;  3
2;       2015-07-20;  2015-07-24;  3
2;       2015-07-26;  2015-08-02;  4
2;       2015-08-03;  2015-08-07;  4

Any help much appreciated.

Regards, Przemek

Gordon Linoff

If you want to just number them, then I would suggest lag() with a cumulative sum:

select t.*,
       sum(case when datefrom = dateadd(day, 1, prev_dateto
                then 0 else 1
           end) over (order by itemId, datefrom)
from (select t.*,
             lag(dateto) over (partition by itemid order by datefrom) as prev_dateto
      from table t
     ) t;

The case determines where a new island begins. The cumulative sum just sums this flag.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事