Have a table in Oracle db such like this:
Word Cnt
A 20
B 25
C 23
B 29
D 31
What I trying to do - is to add an additional column with id of a word. But it is not a primary key it wont be unique because of repeating words. So the outcome I'm looking for is:
Word Cnt ID
A 20 1
B 25 2
C 23 3
B 29 2
D 31 4
How can I perform that in Oracle SQL?
You can use a window function to calculate the ID:
select word,
cnt,
dense_rank() over (order by word) as id
from the_table;
You can update the table using the above, if you really need to persist that:
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;
My solution requires a lot of nested subqueries, but it works...
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
);
如果您的意图只是选择
select word,cnt,count(*) over(partition by word,count) as Id from table_name;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.