我的情况类似于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
最后,我做了一些编码来修改我当前的结果。但我想问一下,有没有办法只通过查询生成预期的结果?
答案 0 :(得分:0)
您可以在查询中添加 CASE COUNT(1)over(按代码分区),请参阅下面的示例查询。
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