根据记录数据更改重置行号

时间:2014-12-28 21:59:58

标签: sql gaps-and-islands

我有一组数据如下

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

我试图得到这个结果

name  date           row_num
x     2014-01-01      1
x     2014-01-02      2
y     2014-01-03      1
x     2014-01-04      1

我试图运行此查询

select name,
       date,
       row_number () over (partition by name order by date) as row_num
from myTBL

但不幸的是我得到了这个结果

name  date           row_num
x     2014-01-01      1
x     2014-01-02      2
y     2014-01-03      1
x     2014-01-04      3

请帮忙。

1 个答案:

答案 0 :(得分:19)

您需要确定一起出现的names组。您可以使用行号的不同来执行此操作。然后,使用grp分区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

对于您的样本数据:

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

这应该让你知道它是如何工作的。