在Oracle db中有一个表,如下所示:
Word Cnt
A 20
B 25
C 23
B 29
D 31
我要做的是添加一个带有单词id的附加列。但它不是一个主要的关键因为重复的话不会是独一无二的。所以我正在寻找的结果是:
Word Cnt ID
A 20 1
B 25 2
C 23 3
B 29 2
D 31 4
如何在Oracle SQL中执行该操作?
答案 0 :(得分:2)
您可以使用窗口函数来计算ID:
select word,
cnt,
dense_rank() over (order by word) as id
from the_table;
如果你真的需要坚持下去,你可以使用上面的表来更新表:
merge into the_table tg
using (
select rowid as rid,
dense_rank() over (order by word) as new_id
from the_table
) t on (t.rid = tg.rowid)
when matched then update
set id = t.new_id;
答案 1 :(得分:1)
我的解决方案需要大量嵌套子查询,但它可以工作......
alter table mytable add (id number(12));
update mytable
set id = (select n from
(select word, rownum n from
(select word from mytable group by word order by word)
) x where mytable.word = x.word
);
答案 2 :(得分:0)
如果您的意图只是选择
select word,cnt,count(*) over(partition by word,count) as Id from table_name;