0

您好我有一个临时表(#temptable1),我想从另一个临时表(#temptable2)中添加一列,我的查询如下:

select 
Customer
,CustName
,KeyAccountGroups
,sum(Weeksales) as Weeksales
into #temptable1
group by Customer
,CustName
,KeyAccountGroups


select
SUM(QtyInvoiced) as MonthTot
,Customer
into #temptalbe2
from SalesSum
where InvoiceDate between @dtMonthStart and @dtMonthEnd
group by Customer


INSERT INTO #temptable1
SELECT MonthTot FROM #temptable2
where #temptable1.Customer = #temptable2.Customer

我得到以下信息:列名或提供的值的数量与表定义不匹配。

4

2 回答 2

0

如果我理解正确,你想做两件事。1:更改表 #temptable1 并添加一个新列。2:用#temptable2 的值填充该列

ALTER #temptable1 ADD COLUMN MothTot DATETIME

UPDATE #temptable1 SET MothTot = (
    SELECT MonthTot 
    FROM #temptable2
    WHERE #temptable2.Customer = #temptable1.Customer)
于 2013-05-08T09:07:19.313 回答
0

INSERT语句中,您不能引用要插入的表。插入是在要创建新行的假设下工作的。这意味着没有可以引用的现有行。

您正在寻找的功能由以下UPDATE语句提供:

UPDATE t1
SET MonthTot = t2.MonthTot 
FROM #temptable1 t1
JOIN #temptable2 t2
ON t1.Customer = t2.Customer;

但是请注意,此逻辑要求 t2 中的 Customer 列是唯一的。如果您在该表中有重复的值,则查询似乎运行良好,但是您最终会得到随机更改的结果。

有关如何在一个中组合两个表的更多详细信息,UPDATE或者DELETE查看我的 A Join A Day - UPDATE & DELETE帖子。

于 2013-05-08T09:20:27.693 回答