2011-08-19 46 views
27

基本上我想運行下面的查詢:的Oracle SQL:在插入使用順序與Select語句

INSERT INTO historical_car_stats (historical_car_stats_id, year, month, make, model, region, avg_msrp, count) 
    SELECT 
    my_seq.nextval, 
    '2010', 
    '12', 
    'ALL', 
    'ALL', 
    region, 
    sum(avg_msrp * count)/sum(count), 
    sum(count) 
    FROM historical_car_stats 
    WHERE year = '2010' 
     AND month = '12' 
     AND make != 'ALL' 
    GROUP BY region; 

它不起作用,因爲「這裏不允許序列號」 SQL錯誤。我怎麼寫這個,所以Oracle會讓我做我想做的事情?

回答

51

假設你要組數據你生成的序列鍵之前,它聽起來就像你想要的東西,像

INSERT INTO HISTORICAL_CAR_STATS (
    HISTORICAL_CAR_STATS_ID, 
    YEAR, 
    MONTH, 
    MAKE, 
    MODEL, 
    REGION, 
    AVG_MSRP, 
    CNT) 
SELECT MY_SEQ.nextval, 
     year, 
     month, 
     make, 
     model, 
     region, 
     avg_msrp, 
     cnt 
    FROM (SELECT '2010' year, 
       '12' month, 
       'ALL' make, 
       'ALL' model, 
       REGION, 
       sum(AVG_MSRP*COUNT)/sum(COUNT) avg_msrp, 
       sum(cnt) cnt 
      FROM HISTORICAL_CAR_STATS 
     WHERE YEAR = '2010' 
      AND MONTH = '12' 
      AND MAKE != 'ALL' 
     GROUP BY REGION) 
+0

如果序列列需要出現在表的中間怎麼辦? – atom

+0

看來,規則是最外層的選擇中不可能有「where」。 – Dariusz

4

我測試和腳本運行OK!

INSERT INTO HISTORICAL_CAR_STATS (HISTORICAL_CAR_STATS_ID, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT) 
WITH DATA IS 
(
    SELECT '2010' YEAR,'12' MONTH ,'ALL' MAKE,'ALL' MODEL,REGION,sum(AVG_MSRP*COUNT)/sum(COUNT) AVG_MSRP,sum(Count) COUNT 
    FROM HISTORICAL_CAR_STATS 
    WHERE YEAR = '2010' AND MONTH = '12' 
    AND MAKE != 'ALL' GROUP BY REGION 
) 
SELECT MY_SEQ.nextval, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT 
FROM DATA; 

你可以閱讀這篇文章瞭解更多! http://www.orafaq.com/wiki/ORA-02287

+2

它的工作原理。但是你有一個小錯誤。它的內容是'WITH DATA IS',它應該是'WITH DATA AS'。 – Fred