Teradata SQL:计算错误代码的连续出现次数(并在未出现时重置)

Teradata SQL: Calculate number of successive occurrences of error code (and reset on non occurrence)

我有一个来源 table,其中包含多个项目的 运行 次以及 运行 期间产生的错误代码。我正在寻找的结果应该显示每个项目的每个错误发生了多少个连续 运行s。如果错误跳过 运行,计数将重置。跑步并不总是连续几天 运行。这个想法是找出连续出现的错误代码,而不是为每个项目重置。

Item    Run Run_date    Err_Code
------------------------------------------
A        1  1/1/2020    ERR1
A        1  1/1/2020    ERR2
A        1  1/1/2020    ERR3
A        2  1/2/2020    ERR1
A        2  1/2/2020    ERR2
A        3  1/3/2020    ERR1
A        3  1/3/2020    ERR2
A        4  1/4/2020    ERR2
A        4  1/4/2020    ERR3
A        5  1/5/2020    ERR1
A        5  1/5/2020    ERR3
B..
B..
B..

Result: 3 cols

Item    Err_Cd  Times
---------------------
A       ERR1    3 (meaning ERR1 occurred thrice in succession for A in runs 1,2,3)
A       ERR1    1 (meaning ERR1 occurred once for A in run 5)
A       ERR2    4 (meaning ERR2 occurred 4 times in succession for A in runs 1,2,3,4)
A       ERR3    1 (meaning ERR3 occurred once for A in run 1)
A       ERR3    2 (meaning ERR3 occurred twice in succession for A in runs 4,5)
B..
B..

感谢任何帮助!谢谢

您可以从日期中减去 row_number() 并合计:

select item, err_cd, count(*)
from (select t.*,
             row_number() over (partition by item, err_cd order by run) as seqnum
      from t
     ) t
group by item, err_cd, run - seqnum
order by item, err_cd, min(run);