我有如下数据集
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
请帮忙.
解决方法
您需要识别一起出现的名称组.您可以使用行号的不同来执行此操作.然后,使用grp对row_number()进行分区:
select name,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
这应该让你知道它是如何工作的.