使用Teradata有条件地重置行计数器

时间:2018-02-05 17:06:35

标签: sql teradata

我已经看过很多与上述类似的问题,但没有一个与我想要做的完全匹配的问题。

哪个是

row_rk    time_sk   date         lagged_date    mycounter
1         1         '31-01-17'   '31-01-17'     1
1         2         '31-01-17'   '31-01-17'     1
1         3         '31-01-17'   '31-01-17'     1
1         4         '28-02-17'   '31-01-17'     2
1         5         '28-02-17'   '28-02-17'     2
1         6         '28-02-17'   '28-02-17'     2
1         7         '31-03-17'   '28-02-17'     3
1         8         '31-03-17'   '31-01-17'     3
1         9         '31-03-17'   '31-01-17'     3

我最接近的是使用:

select 
a.*,
row_number()

over (

partition by row_rk, lagged_date

order by time_sk asc 
 reset when date <> lagged_date
)                                                       as mycounter 
from mytable a
;

这给了我一个值,它用每行数据递增行号,然后在row_rk和滞后日期组合改变时重置它。所以看起来如此:

row_rk    time_sk   date         lagged_date    mycounter
    1         1         '31-01-17'   '31-01-17'     1
    1         2         '31-01-17'   '31-01-17'     2
    1         3         '31-01-17'   '31-01-17'     3
    1         4         '28-02-17'   '31-01-17'     1
    1         5         '28-02-17'   '28-02-17'     2
    1         6         '28-02-17'   '28-02-17'     3
    1         7         '31-03-17'   '28-02-17'     1
    1         8         '31-03-17'   '31-01-17'     2
    1         9         '31-03-17'   '31-01-17'     3

有人可以提供解决方案吗?

谢谢

0 个答案:

没有答案