跨多个表的数据库聚合:纠正求和计算
处理数据库中的多个表时,像 SUM 这样的聚合函数需要仔细处理确保结果准确。例如,一个查询尝试计算两个表(AP 和 INV)中的值之和,这两个表都具有列 [PROJECT] 和 [Value]。所需的输出应类似于:
PROJECT | SUM_AP | SUM_INV
但是,由于求和错误,提供的查询显示了不正确的结果:
SELECT AP.[PROJECT], SUM(AP.Value) AS SUM_AP, SUM(INV.Value) AS SUM_INV FROM AP INNER JOIN INV ON (AP.[PROJECT] =INV.[PROJECT]) WHERE AP.[PROJECT] = 'XXXXX' GROUP BY AP.[PROJECT]
问题在于值的分组。 GROUP BY 子句组合了重复的值,这会导致总和不正确。
要纠正此问题,可以使用子选择:
SELECT AP1.[PROJECT], (SELECT SUM(AP2.Value) FROM AP AS AP2 WHERE AP2.PROJECT = AP1.PROJECT) AS SUM_AP, (SELECT SUM(INV2.Value) FROM INV AS INV2 WHERE INV2.PROJECT = AP1.PROJECT) AS SUM_INV FROM AP AS AP1 INNER JOIN INV AS INV1 ON (AP1.[PROJECT] =INV1.[PROJECT]) WHERE AP1.[PROJECT] = 'XXXXX' GROUP BY AP1.[PROJECT]
此方法单独计算每个 [PROJECT] 的总和] 使用子选择,从而实现准确的聚合。
以上是如何正确聚合多个数据库表中的 SUM 值?的详细内容。更多信息请关注PHP中文网其他相关文章!