ORACLE/PLSQL auto increment

Asked

Viewed 424 times

0

Nome    Idade   ID
João    5       
Lucas   5   
João    2   
Lucas   1   

I would like to use a cursor to sort by names and by age and the ID field to be populated according to the sequence, for example:

Nome    Idade   ID
João    2       1
João    5       2
Lucas   1       1
Lucas   5       2

It’s Possible?

  • can inform the scenario? This information is being entered? are in a select? It was not clear your doubt...

  • This information is present in a table. that would be inserted only the ID

  • Declare
 v_contador number := 0;
 v_min_idade number := 0;
 cursor c_i is
 select t.*, rowid from teste_matheus t order by nome, idade asc;
begin
 for i in c_i loop 
 select min(idade)
 into v_min_idade
 from teste_matheus Where id is null and name = i.name; if i.age = v_min_age and i.id is null then v_counter := v_counter + 1; update teste_matheus t set id = v_counter where id is null and t.name = i.name; END IF; END LOOP; END; .

1 answer

-1

The dense_rank function assigns a ranking to the selected values. In the case of the code below, for each Name, apply a ranking according to the Age, and save this ranking in the ID field.

SELECT Nome, Idade, DENSE_RANK() OVER ( PARTITION BY Nome ORDER BY Idade) AS ID FROM $a$ 
  • Avoid placing code without explanation. I remind you that what is clear to you may not be clear to a reader who comes across the question, and thus may not be able to follow your reasoning.

  • Thank you, Isac! I edited my answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.