Resetting Row number according to record data change

后端 未结 1 428
感情败类
感情败类 2020-12-08 11:48

I have got the set of data as follow

name  date  
x     2014-01-01
x     2014-01-02
y     2014-01-03
x     2014-01-04

and I\'m trying to ge

相关标签:
1条回答
  • 2020-12-08 12:12

    You need to identify the groups of names that occur together. You can do this with a difference of row numbers. Then, use the grp for partitioning the row_number():

    select name, date,
           row_number() over (partition by name, grp order by date) as row_num
    from (select t.*,
                 (row_number() over (order by date) -
                  row_number() over (partition by name order by date)
                 ) as grp
          from myTBL t
         ) t
    

    For your sample data:

    name  date         1st row_number   2nd      Grp
    x     2014-01-01         1           1        0
    x     2014-01-02         2           2        0
    y     2014-01-03         3           1        2
    x     2014-01-04         4           3        1
    

    This should give you an idea of how it works.

    0 讨论(0)
提交回复
热议问题