Oracle:如何重启row_number函数

时间:2014-03-05 14:44:02

标签: oracle row-number

我有一个场景,我需要为按部门,分支,金额和按日期排序的数据分组的数据分配row_number。 如果相同部门的某些日期之后金额重复,则分支,我想将row_number设为1。 你能告诉我如何实现这个目标吗? 当我尝试使用Row_number函数时,编号在某些日期之后仍在继续。

示例数据: 如果使用以下函数row_number() over(Partition by Department, Branch, Amount order by Date)

,这是我得到的行号
Department  Branch  Amount  Date        Row_number()
Dep A       Bran 1  51      25-Oct-12   1
Dep A       Bran 1  45.5    26-Nov-12   1
Dep A       Bran 1  45.5    05-Apr-13   2
Dep A       Bran 1  45.5    06-May-13   3
Dep A       Bran 1  65      07-May-13   1
Dep A       Bran 1  51      26-Aug-13   2
Dep A       Bran 1  51      11-Sep-13   3

但我期待以下顺序输出。

Department  Branch  Amount  Date        Row_number()
Dep A       Bran 1  51      25-Oct-12   1
Dep A       Bran 1  45.5    26-Nov-12   1
Dep A       Bran 1  45.5    05-Apr-13   2
Dep A       Bran 1  45.5    06-May-13   3
Dep A       Bran 1  65      07-May-13   1
Dep A       Bran 1  51      26-Aug-13   1
Dep A       Bran 1  51      11-Sep-13   2

有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

您需要更改识别计算row_number()内的组的方式。

类似的东西:

SQL> with t (Department,  Branch,  Amount,  Date#)
  2  as (
  3  select 'Dep A',   'Bran 1',  51,  to_date('25-10-2012','DD-MM-YYYY') from dual union all
  4  select 'Dep A',  'Bran 1',  45.5,    to_date('26-11-2012','DD-MM-YYYY') from dual union all
  5  select 'Dep A',   'Bran 1',  45.5,    to_date('05-04-2013','DD-MM-YYYY') from dual union all
  6  select 'Dep A',   'Bran 1', 45.5,    to_date('06-05-2013','DD-MM-YYYY') from dual union all
  7  select 'Dep A',   'Bran 1',  65,  to_date('07-05-2013','DD-MM-YYYY') from dual union all
  8  select 'Dep A',   'Bran 1',  51,  to_date('26-08-2013','DD-MM-YYYY') from dual union all
  9  select 'Dep A',   'Bran 1',  51,  to_date('11-09-2013','DD-MM-YYYY') from dual
 10  )
 11  select department, branch, amount, date#, row_number() over(partition by grp order by date#) rn
 12  from (
 13  select department, branch, amount, date#, sum(st_grp) over(order by date#) grp from (
 14  select department, branch, amount, date#, case when amount = lag(amount,1,amount) over(order by date#) then 0 else 1 end st_grp from t
 15  )
 16  )
 17  order by date#
 18  /

DEPAR BRANCH     AMOUNT DATE#            RN                                     
----- ------ ---------- -------- ----------                                     
Dep A Bran 1         51 25.10.12          1                                     
Dep A Bran 1       45,5 26.11.12          1                                     
Dep A Bran 1       45,5 05.04.13          2                                     
Dep A Bran 1       45,5 06.05.13          3                                     
Dep A Bran 1         65 07.05.13          1                                     
Dep A Bran 1         51 26.08.13          1                                     
Dep A Bran 1         51 11.09.13          2