Oracle SQL: Use sequence in insert with Select Statement

后端 未结 2 533
梦谈多话
梦谈多话 2020-12-14 15:19

Basically I want to run the following query:

INSERT INTO historical_car_stats (historical_car_stats_id, year, month, make, model, region, avg_msrp, count)
           


        
相关标签:
2条回答
  • 2020-12-14 16:07

    I tested and the script run ok!

    INSERT INTO HISTORICAL_CAR_STATS (HISTORICAL_CAR_STATS_ID, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT) 
    WITH DATA AS
    (
        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;
    

    you can read this article to understand more! http://www.orafaq.com/wiki/ORA-02287

    0 讨论(0)
  • 2020-12-14 16:14

    Assuming that you want to group the data before you generate the key with the sequence, it sounds like you want something like

    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 讨论(0)
提交回复
热议问题