Prog_2918
Prog_2918

Reputation: 19

update sequence value dynamically - plsql

I have a table with three columns col_a,col_b and col_c. col_a and col_b has values and col_c has null values. I just want to update the col_c with start sequence of col_a corresponding col_b. Expecting values of col_c is shown below. Using cursor to achieve this scenario.

COL_A       COL_B       COL_C

     1          1         1   
     2          1         2  
     3          1         3 
     4          1         4  
     5          1         5  
     6          1         6  
     7          1         7  
     8          1         8  
     9          1         9  
    10          1        10  
   101          2       101
   102          2       102
   104          2       103
   106          2       104
   107          2       105
   108          2       106
   110          2       107
   201          3       201
   202          3       202
   203          3       203
   204          3       204
   205          3       205
   301          5       301
   302          5       302
   305          5       303
   306          5       304

Upvotes: 1

Views: 131

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520908

One approach is to use a correlated subquery which finds, for each COL_B set of records, the minimum COL_A value to start the sequence. To this value we add the appropriate offset using COUNT.

UPDATE yourTable t1
SET COL_C = (SELECT MIN(t2.COL_A) +
                    COUNT(CASE WHEN t2.COL_A < t1.COL_A THEN 1 END)
             FROM yourTable t2
             WHERE t2.COL_B = t1.COL_B);

Upvotes: 1

Popeye
Popeye

Reputation: 35900

You can take advantage of the analytical function as following:

Merge into your_table t
Using
(Select col_a, col_b,
       First_value(col_a) over (partition by col_b order by col_a)
       + row_number() over (partition by col_b order by col_a) - 1 as col_c
   From your_table) S
On (t.col_a = s.col_a and t.col_b = s.col_b)
When matched then 
Update set t.col_c = s.col_c

Cheers!!

Upvotes: 0

Related Questions