简体   繁体   中英

Order-dependant multi-row update in Oracle

I need to Update the Row based on input value

Example : In my Table data like this

 **LOTNUMBER QUANTITY** 
    0000001      30
    0000002      30
    0000003      20
    0000004      20
    0000005      10

Input Value is -20 then

I need to fetch latest lot number and update the Lot number 0000005 to 0 and 0000004 to 10

Then the Output will be

**LOTNUMBER  QUANTITY**
    0000001      30
    0000002      30
    0000003      20
    0000004      10
    0000005      0

Thanks in Advance.

You can combine window functions, CTEs and correlated updates to achieve this, it's ugly and possibly horribly inefficient. I'm no Oracle expert.

update data u set quantity=( 
  with d as 
     ( 
     select lotnumber as l ,  greatest(0,quantity - greatest (0,
     20
     + quantity - sum(quantity) over (order by lotnumber desc))) as v 
     from data
     )  
  select v from d where u.lotnumber=d.l 
);

that "20" in the middle is your input value

fiddle here: http://sqlfiddle.com/#!4/cce2a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM