我有一个主/详细信息表,并希望根据详细信息表更新主表中的一些汇总值。我知道我可以像这样更新它们:
update MasterTbl set TotalX = (select sum(X) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID)
update MasterTbl set TotalY = (select sum(Y) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID)
update MasterTbl set TotalZ = (select sum(Z) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID)
但是,我想在一个声明中这样做:
update MasterTbl set TotalX = sum(DetailTbl.X), TotalY = sum(DetailTbl.Y), TotalZ = sum(DetailTbl.Z)
from DetailTbl
where DetailTbl.MasterID = MasterTbl.ID group by MasterID
但这不起作用。我也尝试过省略“group by”子句的版本。 我不确定我是否遇到了我的特定数据库(Advantage)或我的SQL限制。可能是后者。有人可以帮忙吗?
答案 0 :(得分:24)
试试这个:
Update MasterTbl Set
TotalX = Sum(D.X),
TotalY = Sum(D.Y),
TotalZ = Sum(D.Z)
From MasterTbl M Join DetailTbl D
On D.MasterID = M.MasterID
根据您使用的数据库,如果不起作用,请尝试此操作(这是非标准SQL,但在SQL Server中是合法的):
Update M Set
TotalX = Sum(D.X),
TotalY = Sum(D.Y),
TotalZ = Sum(D.Z)
From MasterTbl M Join DetailTbl D
On D.MasterID = M.MasterID
答案 1 :(得分:5)
为什么要在更新声明中进行分组?你确定这不是导致查询失败的部分吗?试试这个:
update
MasterTbl
set
TotalX = Sum(DetailTbl.X),
TotalY = Sum(DetailTbl.Y),
TotalZ = Sum(DetailTbl.Z)
from
DetailTbl
where
DetailTbl.MasterID = MasterID
答案 2 :(得分:4)
在Oracle中,解决方案将是:
UPDATE
MasterTbl
SET
(TotalX,TotalY,TotalZ) =
(SELECT SUM(X),SUM(Y),SUM(Z)
from DetailTbl where DetailTbl.MasterID = MasterTbl.ID)
不知道你的系统是否也允许这样做。
答案 3 :(得分:3)
您是否尝试过每个字段的子查询:
UPDATE
MasterTbl
SET
TotalX = (SELECT SUM(X) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),
TotalY = (SELECT SUM(Y) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),
TotalZ = (SELECT SUM(Z) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID)
WHERE
....
答案 4 :(得分:2)
试试这个:
update MasterTbl M,
(select sum(X) as sX,
sum(Y) as sY,
sum(Z) as sZ,
MasterID
from DetailTbl
group by MasterID) A
set
M.TotalX=A.sX,
M.TotalY=A.sY,
M.TotalZ=A.sZ
where
M.ID=A.MasterID
答案 5 :(得分:0)
如果您的数据库支持它,如果通过LAN查询,将所有3个更新连接到一个sql字符串将节省服务器往返。因此,如果没有其他工作,这可能会给你一点点改善。典型的“多语句分隔符是分号,例如:
'update x....;update y...;update...z'