SQL Server 2008:查找具有相等值的连续行数

SQL Server 2008: find number of contiguous rows with equal values

我有一个有多个 ID 的 table。每个 Id 都有按顺序索引排列的值。

create table myValues
(
  id  int,
  ind int,
  val int
)

insert into myValues
values
(21, 5, 300),
(21, 4, 310),
(21, 3, 300),
(21, 2, 300),
(21, 1, 345),
(21, 0, 300),
(22, 5, 300),
(22, 4, 300),
(22, 3, 300),
(22, 2, 300),
(22, 1, 395),
(22, 0, 300)

我正在尝试查找相同的连续值的数量。

值字段代表一些应该在每个条目上更改的数据(但不需要整体是唯一的)。

问题是找出何时有超过两个连续的行具有相同的值(给定相同的id)。

因此我正在寻找这样的输出:

id  ind   val   count
21  5     300   1
21  4     310   1
21  3     300   2
21  2     300   2
21  1     345   1
21  0     300   1
22  5     300   4
22  4     300   4
22  3     300   4
22  2     300   4
22  1     395   1
22  0     300   1

我知道这类似于讨论的孤岛和间隙问题 here

但是,这些解决方案都取决于使用分区语句的能力,其值应该是连续增加的。

作为中介生成 "islands" 范围的解决方案也可以,例如

id  startind   endind
21  3          2
22  5          2

请注意,每个 id 可以有多个岛屿。

我确定有一个简单的岛解决方案,但我想不出。

另一个解决方案显然更优雅。我得自己再仔细研究一下。

with agg(id, min_ind, max_ind, cnt) as (
    select id, min(ind), max(ind), count(*)
    from
        (
        select id, ind, val, sum(brk) over (partition by id order by ind desc) as grp
        from
            (
            select 
                id, ind, val,
                coalesce(sign(lag(ind) over (partition by id, val order by ind desc) - ind - 1), 1) as brk
            from myValues
            ) as d
        ) as d
    group by id, grp
)
select v.id, v.ind, v.val, a.cnt
from myValues v inner join agg a on a.id = v.id and v.ind between min_ind and max_ind
order by v.id, v.ind desc;

找到连续的组,然后用它做一个 count() 分区

select  id, ind, val, count(*) over (partition by id, val, grp)
from
(
    select  *, grp = dense_rank() over (partition by id, val order by ind) - ind
    from    myValues
) d
order by id, ind desc