Oracle:连接重复值的序列号

Oracle: Concatenate sequence number for repeated values

我的情况与 this 类似,但我只想为重复值创建序列号。

Table: MyTable
-----------------------
ID  CODE

1   100     

2   100     

3   200     

4   200     

5   200 

6   300

下面是我的查询:

SELECT ID, CODE, (row_number() over (partition by CODE order by ID)) as SEQ from MyTable

这是我目前的结果:

ID  CODE    SEQ

1   100     1

2   100     2

3   200     1

4   200     2

5   200     3

6   300     1

但我的预期结果是:

ID  CODE    SEQ

1   100     1

2   100     2

3   200     1

4   200     2

5   200     3

6   300     

最后,我做了一些编码来修改我当前的结果。但是我想问一下有什么方法可以只通过查询生成预期的结果吗?

您可以在查询中添加 CASE COUNT(1) over (partition by CODE),请参阅下面的示例查询。

WITH MyTable
as (
select 1 id,  100 code from dual union all
select 2 id,  100 code from dual union all
select 3 id,  200 code from dual union all
select 4 id,  200 code from dual union all
select 5 id,  200 code from dual union all
select 6 id,  300 code from dual)
SELECT ID, CODE, CASE COUNT(1) over (partition by CODE)
                    WHEN 1 THEN NULL
                    ELSE row_number() over (partition by CODE order by ID)
                 END as SEQ 
  from MyTable;

        ID       CODE        SEQ
---------- ---------- ----------
         1        100          1
         2        100          2
         3        200          1
         4        200          2
         5        200          3
         6        300           

6 rows selected