Search code examples
sqloraclelogiclaganalytical

sql query logic


I have following data set

       a      b      c
      `1`     2      3
       3      6      9  
       9      2      11 

As you can see column a's first value is fixed (i.e. 1), but from second row it picks up the value of column c of previous record.

Column b's values are random and column c's value is calculated as c = a + b

I need to write a sql query which will select this data in above format. I tried writing using lag function but couldn't achieve.

Please help.

Edit : Column b exists in table only, a and c needs to calculated based on the values of b.

Hanumant


Solution

  • SQL> select a
      2       , b
      3       , c
      4    from dual
      5   model
      6         dimension by (0 i)
      7         measures (0 a, 0 b, 0 c)
      8         rules iterate (5)
      9         ( a[iteration_number] = nvl(c[iteration_number-1],1)
     10         , b[iteration_number] = ceil(dbms_random.value(0,10))
     11         , c[iteration_number] = a[iteration_number] + b[iteration_number]
     12         )
     13   order by i
     14  /
    
             A          B          C
    ---------- ---------- ----------
             1          4          5
             5          8         13
            13          8         21
            21          2         23
            23         10         33
    
    5 rows selected.
    

    Regards,
    Rob.