我有一个主/详细信息表,并希望根据详细信息表更新主表中的一些汇总值.我知道我可以像这样更新它们:
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限制.可能是后者.有人可以帮忙吗?
试试这个:
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
为什么要根据更新语句进行分组?您确定不是导致查询失败的部分吗?尝试这个:
update MasterTbl set TotalX = Sum(DetailTbl.X), TotalY = Sum(DetailTbl.Y), TotalZ = Sum(DetailTbl.Z) from DetailTbl where DetailTbl.MasterID = MasterID