![](/img/trans.png)
[英]SQL Update Query to update a table with aggregate value from another table using multiple fields
[英]Update multiple columns of a table using aggregate values from another table
我有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语句的集合列表中”。 关于如何实现这一点的任何建议。
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;
如何将其移动到子查询中?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.