我正在尝试编写一个查询,从表中提取和转换数据,然后将这些数据插入另一个表.是的,这是一个数据仓库查询,我在MS Access中这样做.所以基本上我想要一些像这样的查询:
INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) VALUES (SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1);
我试过但得到语法错误消息.
如果你想这样做,你会怎么做?
没有"价值",没有括号:
INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1;
您有两种语法选项:
选项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
选项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
请记住,选项2将创建一个只包含投影列(SELECT上的列)的表.
删除VALUES和括号.
INSERT INTO Table2 (LongIntColumn2, CurrencyColumn2) SELECT LongIntColumn1, Avg(CurrencyColumn) FROM Table1 GROUP BY LongIntColumn1
VALUES
从SQL中删除.
我相信你在这个例子中的问题是"值"关键字.只插入一行数据时使用"values"关键字.要插入选择的结果,您不需要它.
另外,你真的不需要围绕select语句的括号.
来自msdn:
多记录追加查询:
INSERT INTO target [(field1[, field2[, …]])] [IN externaldatabase] SELECT [source.]field1[, field2[, …] FROM tableexpression
单记录追加查询:
INSERT INTO target [(field1[, field2[, …]])] VALUES (value1[, value2[, …])