SQL查询:从选择结果更新

时间:2016-03-17 10:21:54

标签: sql-server select sql-update

这是我的SQL查询

UPDATE dbo.TD_TOTAL_ACCOUNTS SET Total_Accounts = Total 
SELECT annee, mois,[Group],
(
 SELECT SUM(Accounts_Number) 
FROM olap.TD_ALL_ACCOUNTS 
WHERE EOMONTH(cast( cast(mois as nvarchar(2))+ '/' + '01'  + '/' + cast(annee as nvarchar(4)) as DATETIME)) <= EOMONTH(cast( cast(T2.mois as nvarchar(2))+ '/' + '01'  + '/' + cast(T2.annee as nvarchar(4)) as DATETIME)) AND [Group] = T2.[Group]
) AS Total 
FROM olap.TD_ALL_ACCOUNTS AS T2

&#34; Total&#34;列无法识别。我无法命名选择T3的表格,并在SET&#34; Total_Accounts = T3.Total&#34;中使用它。

提前谢谢。

1 个答案:

答案 0 :(得分:1)

这样的事情可以解决问题(将IdColumn更改为行标识符),但我强烈建议您考虑Lad2025评论。

UPDATE t 
SET Total_Accounts = Total 
FROM dbo.TD_TOTAL_ACCOUNTS t 
INNER JOIN
(
SELECT IdColumn, annee, mois,[Group],
(
 SELECT SUM(Accounts_Number) 
FROM olap.TD_ALL_ACCOUNTS 
WHERE EOMONTH(cast( cast(mois as nvarchar(2))+ '/' + '01'  + '/' + cast(annee as nvarchar(4)) as DATETIME)) <= EOMONTH(cast( cast(T2.mois as nvarchar(2))+ '/' + '01'  + '/' + cast(T2.annee as nvarchar(4)) as DATETIME)) AND [Group] = T2.[Group]
) AS Total 
FROM olap.TD_ALL_ACCOUNTS AS T2
) T3 ON(t.IdColumn = T3.IdColumn)