2013-01-17 89 views
1

我試圖從視圖MYVIEW1和MYVIEW2插入一些字段到MYTABLE,然後從一個參數(這是存儲過程的一部分)添加一個值爲UPDATED_BY,SYSDATE爲UPDATED_ON。我如何正確使用INSERT SELECT或其他方式完成此操作?ORACLE:INSERT SELECT FROM 2 views and value from param

MYVIEW1  
+------+----+-----+-----------+---------+ 
| YR | MO | QTR | USER_CODE | MO_PERF | 
+------+----+-----+-----------+---------+ 
| 2012 | 1 | 1 |  1099 |  89 | 
| 2012 | 2 | 1 |  1099 |  86 | 
| 2012 | 3 | 1 |  1099 |  95 | 
+------+----+-----+-----------+---------+ 
MYVIEW2  
+------+-----+-----------+----------+ 
| YR | QTR | USER_CODE | QTR_PERF | 
+------+-----+-----------+----------+ 
| 2012 | 1 |  1099 |  90 | 
+------+-----+-----------+----------+ 

MYTABLE 
+------+-----+-----------+---------+---------+---------+---------+-------------+------------+ 
| YR | QTR | USER_CODE | MO1_PCT | MO2_PCT | MO3_PCT |  INC | UPDATED_BY | UPDATED_ON | 
+------+-----+-----------+---------+---------+---------+---------+-------------+------------+ 
| 2012 | 1 |  1099 |  89 |  86 |  95 | 7000 | SAMPLE NAME | 01/16/2013 | 
+------+-----+-----------+---------+---------+---------+---------+-------------+------------+ 

INSERT INTO MYTABLE 
(YR,QTR,USER_CODE,MO1_PCT,MO2_PCT,MO3_PCT,INC,UPDATED_BY,UPDATED_ON) 
    SELECT b.YR,b.QTR,b.USER_CODE,b.MO1_PCT,b.MO2_PCT,b.MO3_PCT,c.INC 
    FROM MYVIEW1 b, 
     MYVIEW2 c 

如何插入的值(第一個月QTR的MO_PERF)爲MO1_PCT和(QTR的MO_PERF的第二個月)爲MO2_PCT和(QTR的MO_PERF的最後一個月)爲MO3_PCT,確保我插在正確的季度和正確的一個月內。然後檢查每個月的MO_PERF值是否至少達到85,否則將INC設置爲NULL。

,CASE WHEN MO1_PCT>=85 AND MO2_PCT>=85 AND MO3_PCT>=85 THEN 7000 
ELSE NULL 
END INC 

回答

3

如果您正在使用Oracle 11g,那麼你可以使用PIVOT這樣的:

select YR, QTR, USER_CODE, "1_MO_PCT" MO1_PCT, "2_MO_PCT" MO2_PCT, "3_MO_PCT" MO3_PCT , 
case when "1_MO_PCT" >= 85 and "2_MO_PCT" >= 85 and "2_MO_PCT" >= 85 then 7000 end INC, 
user updated_by, sysdate updated_on 
from (
select m1.yr, m1.mo, m1.qtr, m1.user_code, m1.mo_perf, m2.qtr_perf 
from myview1 m1 join myview2 m2 on m1.yr=m2.yr 
and m1.qtr = m2.qtr and m1.user_code = m2.user_code)t 
pivot(
    max(mo_perf) MO_PCT for mo in (1,2,3) 
) 

Here is a sqlfiddle demo

+0

非常好,謝謝。我會研究這個關鍵的東西。 – esandrkwn

+0

但最後一個問題。我需要做4次,每年的每個季度做一次?什麼應該是正確的方式來做到這一點? – esandrkwn

+1

我不明白 - 你的意思是你想每個月都有專欄?我認爲'MYVIEW2'擁有相關的宿舍,所以加入時會爲每個季度創建一個行,並在該季度的每個月(3列)中添加一列,如同這個sqlfiddle http://www.sqlfiddle.com/#! 4/72d2b/1 –

相關問題