Teradata中如何统计一个元素在table中连续出现的次数?

How to count the number of times an element appears consecutively in a table in Teradata?

我有一个 table 看起来像这样

ID, Order, Segment
1, 1, A
1, 2, B
1, 3, B
1, 4, C
1, 5, B
1, 6, B
1, 7, B
1, 8, B

基本上是使用“顺序”列对数据进行排序。我想了解每个 ID 的连续 B 的数量。理想情况下,我想要的输出是

ID, Consec
1, 2
1, 4

因为段B连续出现在第2行和第3行(2次),然后又出现在第5、6、7、8行(4次)。

我想不出 SQL 中的解决方案,因为 SQL 中没有循环设施。

Teradata 中是否有优雅的解决方案SQL?

P.S。我正在处理的数据有大约 2000 万行。

在 R 中执行此操作的方法已在此处发布。

How to count the number of times an element appears consecutively in a data.table?

解析函数很容易做到。虽然我对 teradata 一无所知,但快速谷歌搜索让它看起来好像确实支持分析功能。

无论如何,我已经在 Oracle 中测试了以下内容 --

  select id,
         count(*)
    from (select x.*,
                 row_number() over(partition by id order by ord) -
                 row_number() over(partition by id, seg order by ord) as grp
            from tbl x) x
   where seg = 'B'
group by id, grp
order by grp

诀窍是建立 Bs 的 'groups'。

Fiddle: http://sqlfiddle.com/#!4/4ed6c/2/0