I'm trying to write a query that extracts and transforms data from a table and then inserts that data into another table. Yes, this is a data warehouse query and I executed it in MS Access. So basically I want some query like this:
INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) VALUES (SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1);
I tried it but got a syntax error message.
If you wanted to do this, what would you do?
P粉9492671212023-10-11 14:11:14
You have two syntax options:
Option 1
CREATE TABLE Table1 ( id int identity(1, 1) not null, LongIntColumn1 int, CurrencyColumn money ) CREATE TABLE Table2 ( id int identity(1, 1) not null, LongIntColumn2 int, CurrencyColumn2 money ) INSERT INTO Table1 VALUES(12, 12.00) INSERT INTO Table1 VALUES(11, 13.00) INSERT INTO Table2 SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1
Option 2
CREATE TABLE Table1 ( id int identity(1, 1) not null, LongIntColumn1 int, CurrencyColumn money ) INSERT INTO Table1 VALUES(12, 12.00) INSERT INTO Table1 VALUES(11, 13.00) SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 INTO Table2 FROM Table1 GROUP BY LongIntColumn1
Remember that option 2 will create a table containing only the columns on the projection (the columns on the SELECT).
P粉3221067552023-10-11 10:09:04
No "VALUES", no brackets:
INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1;