簡體   English   中英

將行拆分為多行PL / SQL

[英]Split rows into multiple rows PL/SQL

有沒有一種簡單的方法可以將一行的值分成多行? 例如,假設我有下表

項目日期數量類型
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

我要做的是取類型4或5的那些物品,取其數量,將所述數量除以類型(例如5000/5),然后在接下來的n周內平均分配結果,具體取決於類型(例如,類型5為5周,類型4為4周)。 最后,取得分割結果並將其添加到該周的任何其他結果中。

例如,我們在7月份有6000個項目2001。 每周將有1000數量的項目2001,但從7/6開始的那一周將有2000。

這是我正在尋找的輸出

輸出看起來像這樣

項目日期數量
2001 7/1/2014 1000
2001 7/6/2014 2000(上表中為拆分的1000,類型1中為1000)
2001 7/13/2014 1000
2001 7/20/2014 1000
2001 7/27/2014 1000

我不太確定要雇用。 我懷疑帶有循環的子查詢將是一個開始。

這一步非常接近,但拆分恰好可以追溯到7,14,21,28天。 在您的示例中,7/6/14從7/1/14獲得1000,下面的語句將不提供該語句,因為2014年7月1日的分割結果為7/8 / 2014、7 / 15/2014等也許這只是您的問題中的一點疏忽; 否則,查詢需要做更多的工作才能更好地匹配日期。

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM