我有2个表,我试图首先使用第二个表上的聚合函数进行更新。下面是代码: -
Update temp1 t1
set t1.Margin = SUM(t2.Margin2),
t1.Revenue = SUM(t2.Revenue2),
t1.Sales = SUM (t2.Sales2),
t1.Revenue = SUM (t2.Revenue2)
from t1 inner join tempcost t2
on t1.P_Id = t2.P_Id
显示错误“聚合可能不会出现在UPDATE语句的集合列表中”。 关于如何实现这一目标的任何建议。
答案 0 :(得分:5)
MySQL中的正确语法:
Update temp1 t1 join
(select p_id, SUM(t2.Margin2) as margin2, SUM(t2.Revenue2) as revenue2,
SUM(t2.Sales2) as sales2
from tempcost t2
group by p_id
) t2
on t1.P_Id = t2.P_Id
set t1.Margin = t2.margin2,
t1.Revenue = t2.Revenue2,
t1.Sales = t2.Sales2;
SQL Server中的正确语法:
Update t1
set Margin = t2.margin2,
Revenue = t2.Revenue2,
Sales = t2.Sales2
from temp1 t1 join
(select p_id, SUM(t2.Margin2) as margin2, SUM(t2.Revenue2) as revenue2,
SUM(t2.Sales2) as sales2
from tempcost t2
group by p_id
) t2
on t1.P_Id = t2.P_Id;
答案 1 :(得分:1)
如何将其移动到子查询中?
Update temp1 t1
set t1.Margin = t2.Margin
,t1.Revenue = t2.Revenue
,t1.Sales = t2.Sales2
from t1
join (
SELECT
SUM(Margin2) as Margin
,SUM(Revenue2) as Revenue
,SUM(Sales2) as Sales
FROM tempcost
) t2
on t1.P_Id = t2.P_Id