How to do INSERT into a table records extracted from another table How to do INSERT into a table records extracted from another table sql sql

How to do INSERT into a table records extracted from another table


No "VALUES", no parenthesis:

INSERT INTO Table2(LongIntColumn2, CurrencyColumn2)SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1;


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 Table2SELECT 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 CurrencyColumn1INTO Table2FROM Table1GROUP BY LongIntColumn1

Bear in mind that Option 2 will create a table with only the columns on the projection (those on the SELECT).


Remove both VALUES and the parenthesis.

INSERT INTO Table2 (LongIntColumn2, CurrencyColumn2)SELECT LongIntColumn1, Avg(CurrencyColumn) FROM Table1 GROUP BY LongIntColumn1