简体   繁体   中英

Split rows into multiple rows PL/SQL

Is there an easy way to split the value of a row into multiple rows? For example, let's say I have the following table

Item Date Quantity Type
2001 7/1/2014 5000 5
2001 7/6/2014 1000 1
2002 7/20/2014 3000 1
2003 7/1/2014 2000 5
2004 8/3/2014 4000 4

What I'm looking to do is take those items that are either type 4 or 5, take their quantities, divide said quantities by the type (eg, 5000/5) and distribute the result evenly across the next n weeks, depending on the type (ie, 5 weeks for type 5 and 4 weeks for type 4). Lastly, take that split result and add it to any other results in that week.

For example, we have 6000 of item 2001 for the month of July. Each week would have 1000 quantity of item 2001, except for the week starting 7/6 where there would be 2000.

Here is the output I'm seeking

The output would look something like this

Item Date Quantity
2001 7/1/2014 1000
2001 7/6/2014 2000 (1000 from the split and 1000 from Type 1 in the table above)
2001 7/13/2014 1000
2001 7/20/2014 1000
2001 7/27/2014 1000

I'm not really sure to employ. I suspect a subquery with a loop would be a start.

This one comes pretty close, but the split goes back exactly 7,14,21,28 days. In your example, 7/6/14 gets 1000 from 7/1/14, which the statement below wouldn't provide, since the split of 7/1/2014 goes to 7/8/2014, 7/15/2014 etc. Maybe this was just a little oversight in your question; otherwise, the query needs a bit more work to better match the dates.

create table sales (item number(4), sdate date, quantity number, stype number(1));

with dategenerator as (select to_date('1.1.2014')+(rownum-1) sdate from dual connect by rownum<=365),
prodlist as (select distinct item from sales),
salessplitted as (
select prodlist.item, dategenerator.sdate, 
   (select nvl(sum(quantity),0) from sales where sdate=dategenerator.sdate and item=prodlist.item and stype=1)+
   (select nvl(sum(quantity/4),0) from sales where sdate in (dategenerator.sdate,dategenerator.sdate-7,dategenerator.sdate-14,dategenerator.sdate-21) and item=prodlist.item and stype=4)+
   (select nvl(sum(quantity/5),0) from sales where sdate in (dategenerator.sdate,dategenerator.sdate-7,dategenerator.sdate-14,dategenerator.sdate-21,dategenerator.sdate-28) and item=prodlist.item and stype=5) total
  from dategenerator, prodlist )
select item, sdate, total from salessplitted where total>0
order by item, sdate;

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