我想用另一个表中的数据更新表
表1 OverseasOperation
和表2为ForecastTotal
我使用了这个命令但它只复制了第一个值
Update ForecastTotal
Set OVERSEASVol = Sales
From OverseasOperation
结果是Sales
= OVERSEASVol
结果是
但我想得到像这样的表
出了什么问题?
注意:我想更新不插入,并且不想创建条件,因为我想要复制所有数据
答案 0 :(得分:0)
最通用的方法是使用相关子查询:
Update ForecastTotal
Set OVERSEASVol = (select Sales
from OverseasOperation oo
where oo.?? = ForecastTotal.??
);
??
用于连接条件。目前还不清楚哪些列用于连接两个表。
注意:许多数据库支持在update
语句中连接表的某种方法。这些方法往往依赖于数据库。
答案 1 :(得分:0)
试试吧
;with ForecastTotal_Temp
as
(
select ForecastTotal.OVERSEASVol as OVERSEASVol, row_number() over (order by OVERSEASVol) as rownum
from ForecastTotal
)
update ForecastTotal_Temp
set OVERSEASVol = (
select sub.Sales
from (select OverseasOperation.Sales AS Sales, row_number() over(order by Sales ) as rnum from OverseasOperation) sub
where sub.rnum=ForecastTotal_Temp.rownum
)
答案 2 :(得分:0)
假设表共享一个唯一的公共密钥(称之为ukey),那么
update ForecastTotal
set sales = OverseasOperation.Sales
from ForecastTotal
join OverseasOperation on ForecastTotal.ukey = OverseasOperation.ukey
如果OverSeasOperation有多次出现来自ForecastTotal的主键,则必须对销售额进行求和,在主键上分组,并将wiill用作连接上的第二个表,如下所示
update ForecastTotal
set sales = oo.Sales
from ForecastTotal
join
(
select ukey, sum(Sales) sales
from OverseasOperation
group by ukey
) oo
on ForecastTotal.ukey = oo.ukey
此外,如果您希望通过添加OverseasOperation的销售额来更新ForecastTotal销售额,请更改
中的设置set sales = OverseasOperation.Sales
到
set sales = sales + OverseasOperation.Sales