Oracle SQL将一条记录拆分为多条记录

时间:2017-03-14 14:37:15

标签: plsql oracle11g

假设我有一张像这样的记录表:

ID  Yr      MonthNumber     Type                Amount
2   2020                    Annual Forecast     12,000

然后,假设我想从表中删除此记录,并按照每月频率均匀插入相同的值:

ID  Yr      MonthNumber     Type                Amount
4   2020    1               Monthly Forecast    1,000
5   2020    2               Monthly Forecast    1,000
6   2020    3               Monthly Forecast    1,000
7   2020    4               Monthly Forecast    1,000
8   2020    5               Monthly Forecast    1,000
9   2020    6               Monthly Forecast    1,000
10  2020    7               Monthly Forecast    1,000
11  2020    8               Monthly Forecast    1,000
12  2020    9               Monthly Forecast    1,000
13  2020    10              Monthly Forecast    1,000
14  2020    11              Monthly Forecast    1,000
15  2020    12              Monthly Forecast    1,000

有没有简单的方法来实现这一目标?我有一个包含月度和年度数据的表,所以我想让频率完全相同。也许一个程序开始'For Each Row,Type ='Annual Forecast'......但我不知道正确的语法。

更新:最终解决方案 我放入了在这种情况下使用的真实字段。答案受以下HepC解决方案的启发。谢谢!

INSERT INTO STG_DFF_B("Forecast Month","Publish Date","FinancialPlanType","Subaccount","ITN","Project ID","Resource Type","Details",UNIT,VALS,MONTHNUMBER,"YR")
SELECT "Forecast Month",
    "Publish Date",
    "FinancialPlanType",
    "Subaccount",
    ITN,
    "Project ID",
    "Resource Type",
    "Details",
    UNIT,
    ROUND(VALS/12,2),
    x.lvl,
    "YR"
FROM STG_DFF_B
CROSS JOIN (SELECT LEVEL AS lvl -- Joins in 1 through 12.
           FROM dual
         CONNECT BY LEVEL <= 12) x
WHERE MONTHNUMBER is null;

2 个答案:

答案 0 :(得分:2)

鉴于您所描述的要求和数据质量,我可能会采取以下措施。

INSERT INTO sample_table
SELECT sample_seq.nextval
      ,st.yr
      ,x.lvl
      ,'Monthly Forecast'
      ,st.amount / 12 -- Maybe with ROUND or TRUNC? Depends.
  FROM sample_table st
 CROSS JOIN (SELECT LEVEL AS lvl -- Joins in 1 through 12.
               FROM dual
             CONNECT BY LEVEL <= 12) x
 WHERE st.type = 'Annual Forecast'
   AND NOT EXISTS (SELECT NULL -- Not already present as month (reentrant scripting)
                     FROM sample_table stm
                    WHERE stm.yr = st.yr
                      AND stm.monthnumber IS NOT NULL);

DELETE FROM sample_table st WHERE st.type = 'Annual Forecast';

答案 1 :(得分:0)

稍微修改一下。希望这也有帮助。

INSERT INTO DUMM
SELECT level+a.id id,
  a.yr,
  level,
  'Monthly Forecast' TYP,
  ROUND(a.amt/12) amt
FROM DUMM a
  CONNECT BY level <= DECODE(a.TYP,'Annual Forecast',12,'Monthly Forecast',6,'Quarterly Forecast',4);

DELETE DUMM WHERE TYP = 'Annual Forecast';