基本的に、次のクエリを実行します。
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がやりたいことをできるようにするにはどうすればよいですか?
シーケンスでキーを生成する前にデータをグループ化すると仮定すると、次のようになります
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)
テストし、スクリプトは正常に実行されました!
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;
この記事を読んでさらに理解することができます! http://www.orafaq.com/wiki/ORA-02287