Link to home
Start Free TrialLog in
Avatar of mrong
mrong

asked on

Update number field in Oracle

Greeting,

I have the following table in oracle
acct     dept   seq
001      555      1
002      555      1
003      555      1
004      666      1

How to update the seq field to get the following output?

acct     dept   seq
001      555      1
002      555      2
003      555      3
004      666      1
Avatar of johnsone
johnsone
Flag of United States of America image

There might be a better way, but this seems to work.
UPDATE tab1 a 
SET    seq = (SELECT seq 
              FROM   (SELECT acct, 
                             dept, 
                             Row_number() 
                               over ( 
                                 PARTITION BY dept 
                                 ORDER BY dept, acct) seq 
                      FROM   tab1) b 
              WHERE  a.acct = b.acct 
                     AND a.dept = b.dept); 

Open in new window

Avatar of mrong
mrong

ASKER

got the following error with quggested query.

cannot update ("tab1"."seq") to NULL
Avatar of mrong

ASKER

replaced Row_number() to rownum. got the following error

                               over(
                                   *
ERROR at line 6:
ORA-00923: FROM keyword not found where expected
That tells me that your SEQ column has a not null constraint and that either the ACCT or DEPT column has a NULL in it (or both columns).  What do you want to do in that case?  The easiest thing to do in that case is to default it to 1, but if you have multiple NULLs with the same ACCT/DEPT, they would all get a 1.
UPDATE tab1 a 
SET    seq = Nvl((SELECT seq 
                  FROM   (SELECT acct, 
                                 dept, 
                                 Row_number() 
                                   over ( 
                                     PARTITION BY dept 
                                     ORDER BY dept, acct) seq 
                          FROM   tab1) b 
                  WHERE  a.acct = b.acct 
                         AND a.dept = b.dept), 1); 

Open in new window

Avatar of mrong

ASKER

all the records has seq=1 in the table now. No null values.
Avatar of mrong

ASKER

what does this mean?

SET    seq = Nvl((SELECT seq
                  *
ERROR at line 2:
ORA-01427: single-row subquery returns more than one row
ASKER CERTIFIED SOLUTION
Avatar of johnsone
johnsone
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
It may be helpful to provide a greater variety of sample data that includes nulls, duplicates, etc. plus the expected results from that data.