Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle SQL: Use sequence in insert with Select Statement

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)   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; 

It doesn't work because "sequence number not allowed here" SQL error. How can I write this so Oracle will let me do what I want to do?

like image 452
Muhd Avatar asked Aug 19 '11 18:08

Muhd


People also ask

How do you use a sequence Nextval in a select statement?

You can access the value of a sequence using the NEXTVAL or CURRVAL operators in SQL statements. You must qualify NEXTVAL or CURRVAL with the name (or synonym) of a sequence object that exists in the same database, using the format sequence. NEXTVAL or sequence. CURRVAL.

How do you insert a sequence of numbers in SQL?

The syntax to create a sequence in SQL Server (Transact-SQL) is: CREATE SEQUENCE [schema.] sequence_name [ AS datatype ] [ START WITH value ] [ INCREMENT BY value ] [ MINVALUE value | NO MINVALUE ] [ MAXVALUE value | NO MAXVALUE ] [ CYCLE | NO CYCLE ] [ CACHE value | NO CACHE ]; AS datatype.

How can use insert in sequence statement in SQL Server?

Sequence is used to generate database-wide sequential number, but identity column is tied to a table. Sequence is not associated with a table. Same sequence can be used in multiple tables. It can be used in insert statement to insert identity values, it can also be used in T-Sql Scripts.


1 Answers

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) 
like image 187
Justin Cave Avatar answered Oct 17 '22 16:10

Justin Cave