Search code examples
sqloracle-databasesql-updatesubsetsubtotal

update a field based on subtotal from another table


I'm using oracle(10).

I've got two tables as follows:

Table1 (uniq rows):
ID    AMOUNT     DATE 

Table2:
ID    AMOUNT1 AMOUNT2 ...AMOUNTN DATE

Table2 is connected many to one to Table1 connected via ID.

What I need is update-ing Table1.DATE with: the last (earliest) date from Table2 where Table1.AMOUNT - SUM(Table2.AMOUNT1) <= 0, when reading table 2 backwards by the Table2.DATE field.

Is there a simple way to do it?

Thanks in advance!

UPDATE: as I see from your answers I had misspecified the question a bit. So here goes a detailed example:

Table1 has:

ID: 1     AMOUNT:100    DATE:NULL

Table2 has (for ID: 1 so ID is not listed in here):

AMOUNT1     DATE
50          20080131
30          20080121
25          20080111
20          20080101

So in this case I need 20080111 as the DATE in Table1 as 50+30+25 => 100.


Solution

  • Based on your revised question, this is a case for using analytic functions.

    Assuming you meant >=100 rather than <= 100 as your example implies, and renaming columns DATE to THEDATE since DATE is a reserved word in Oracle:

    update table1 set thedate=
    ( select max(thedate) from
      ( select id, thedate,
               sum(amount1) over (partition by id  order by thedate desc) cumsum
        from table2
      ) v
      where v.cumsum >= 100
      and v.id = table1.id
    )
    

    If the 100 means the current value of table1 then change that line to:

      where v.cumsum >= table1.amount