Sql 按值组的连续日期范围对行进行分组

Sql 按值组的连续日期范围对行进行分组,sql,sql-server,gaps-and-islands,Sql,Sql Server,Gaps And Islands,考虑一些表T,按Col1,Col2,Date1,Date2排序: Col1 Col2 Date1 Date2 rate ABC 123 11/4/2014 11/5/2014 -90 ABC 123 11/4/2014 11/6/2014 -55 ABC 123 11/4/2014 11/7/2014 -90 ABC 123 11/4

考虑一些表
T
,按
Col1,Col2,Date1,Date2
排序:

Col1    Col2    Date1         Date2          rate
ABC     123     11/4/2014     11/5/2014      -90
ABC     123     11/4/2014     11/6/2014      -55
ABC     123     11/4/2014     11/7/2014      -90
ABC     123     11/4/2014     11/10/2014     -90
我希望对数据进行分组,以便轻松审核更改/减少重复,因此

Col1    Col2    Date1         start_Date2    end_Date2      rate
ABC     123     11/4/2014     11/5/2014      11/5/2014      -90
ABC     123     11/4/2014     11/6/2014      11/6/2014      -55
ABC     123     11/4/2014     11/7/2014      11/10/2014     -90
如果我能得到另一列,其中的行编号为
1233
(重要的是数字是不同的),然后按该列分组,我就可以很容易地做到这一点

我的查询尝试:

SELECT *, DENSE_RANK() OVER (ORDER BY rate) island
FROM T
ORDER BY Date2
没有给出我想要的:

Col1    Col2    Date1         Date2          rate     island
ABC     123     11/4/2014     11/5/2014      -90      1
ABC     123     11/4/2014     11/6/2014      -55      2
ABC     123     11/4/2014     11/7/2014      -90      1
ABC     123     11/4/2014     11/10/2014     -90      1
我希望查询能够识别第二组
-90
值应被视为一个新组,因为它们出现在具有不同
速率的组之后


[gaps and islands]SQL标记非常有用,但我不太清楚当速率恢复到以前的值时如何处理。我应该如何修改我的查询?

您可以使用
行数()的差异来识别组。连续值将具有常量

select col1, col2, date1, min(date2), max(date2), rate
from (select t.*,
             (row_number() over (partition by col1, col2, date1 order by date2) -
              row_number() over (partition by col1, col2, date1, rate order by date2)
             ) as grp
      from table t
     ) t
group by col1, col2, date1, rate, grp

你可能会对此感兴趣,因为你可能会对此感兴趣