Q:

Row number for increasing timestmap in hive

I have table like this :
col1    col2
1      2020-01-15
1      2020-01-16
1      2020-01-17
1      2020-01-18
1      2020-01-20
2      2020-01-09
2      2020-01-10
2      2020-01-15

and i am calcuating rank like this
select
    col1,
    col2,
    date_sub(col2, -row_number() over (partition by col1 order by col2)) as rnk
  from myTable

and getting rank
col1    col2        rnk
1      2020-01-15   1
1      2020-01-16   2
1      2020-01-17   3
1      2020-01-18   4
1      2020-01-20   5
2      2020-01-09   1
2      2020-01-10   2
2      2020-01-15   3

but i need rank like this
col1    col2        rnk
1      2020-01-15   1
1      2020-01-16   2
1      2020-01-17   3
1      2020-01-18   4
1      2020-01-20   1
2      2020-01-09   1
2      2020-01-10   2
2      2020-01-15   1

changing whenever consecutive date change like 18 and 20 are not consecutive for user 1 so it is supoose to change
I am not sure how to achieve this

A:

You can use:
select t.*,
       row_number() over (partition by col1, date_add(col2, - seqnum) order by col2) as rank
from (select t.*, row_number() over (partition by col1 order by col2) as seqnum
      from t
     ) t;

The outer row_number() subtracts a sequence from col2.  The result is a constant when there are no gaps in adjacent values.  So, the difference defines the "islands" of adjacent records.

