【问题标题】:How to count the number of times an element appears consecutively in a table in Teradata?如何计算元素在 Teradata 表中连续出现的次数?
【发布时间】:2015-04-16 00:08:50
【问题描述】:

我有一张像这样的表

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

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

ID, Consec
1, 2
1, 4

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

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

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

附:我正在处理的数据有大约 2000 万行。

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

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

【问题讨论】:

    标签: sql teradata


    【解决方案1】:

    使用分析函数很容易做到。虽然我对 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 的“组”。

    小提琴:http://sqlfiddle.com/#!4/4ed6c/2/0

    【讨论】:

    • 如果 ord 实际上是一个完整的唯一序列,你可以这样做 ord - row_number() over(partition by id, seg order by ord) as grp 另外,我相信你可以安全地将 seg 列添加到最终输出,方法是将其附加到列到group by
    • 或者只是 row_number() - row_number() over(partition by id, seg order by ord) as grp
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    相关资源
    最近更新 更多