2013-05-08 75 views
0

您好我有一個臨時表(#temptable1),我想從另一個臨時表中添加一列(#temptable2)成,我的查詢如下:牛逼SQL SELECT到現有表新列

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 

我收到以下內容:列名或提供的值數量與表定義不匹配。

+0

[檢查這個帖子,](http://stackoverflow.com/questions/1152932/column-name-or-number-of-supplied-values-does-not-match-table-definition) 我認爲你面臨同樣的問題 – gefrag 2013-05-08 09:08:24

回答

0

填寫值的列在INSERT聲明中不能引用要插入到表中。插入在假定要創建新行的情況下工作。這意味着沒有可以引用的現有行。

你正在尋找由UPDATE聲明中提供的功能:

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

注意但是,這一邏輯需要客戶列T2是唯一的。如果在該表中有重複的值,則查詢看起來運行良好,但是最終會隨機更改結果。

有關如何組合UPDATEDELETE中的兩個表格的更多詳細信息,請查看我的A Join A Day - UPDATE & DELETE後。

0

如果我理解正確,你想做兩件事。 1:改變表#temptable1並添加一個新列。 2:用#temptable2

ALTER #temptable1 ADD COLUMN MothTot DATETIME 

UPDATE #temptable1 SET MothTot = (
    SELECT MonthTot 
    FROM #temptable2 
    WHERE #temptable2.Customer = #temptable1.Customer) 
+0

嗨我更新#temptable1,以便所有的NULL值爲零,但現在我得到無效的列名稱'Monthtot'。 – Wilest 2013-05-08 09:12:22

+0

@wilest用你的#temptable1描述更新你的問題。我認爲你的#temptable1有一個Monthtot列。 – 2013-05-08 09:15:16

+0

不,我想從temptable2添加一個新列到temptable1,我會更新我的問題 – Wilest 2013-05-08 09:17:35