sql求多个表的数据求和
我有 2 个表 AP 和 INV,其中都有 [PROJECT] 和 [Value] 列。
我想要一个查询返回类似这样的内容:
PROJECT |总和_AP | SUM_INV
我想出了下面的代码,但它返回了错误的结果( sum 是错误的)。
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]
I have 2 tables AP and INV where both have the columns [PROJECT] and [Value].
I want a query to return something like this :
PROJECT | SUM_AP | SUM_INV
I came up with the code below but it's returning the wrong results ( sum is wrong ).
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]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您的查询结果是错误的,因为您尝试汇总的值正在分组,这会导致
SUM
中包含重复的值。您可以通过几个子选择来解决它:
The results from your query are wrong because the values you are trying to summarize are being grouped, which causes duplicate values to be included in the
SUM
.You could solve it with a couple of sub-selects:
如果 AP 中具有给定项目 ID 的
N
行,并且 INV 中具有该 ID 的M
行,则项目 ID 上的两个表之间的联接将具有该项目总共N*M
行,因为 AP 中的同一行将针对 INV 中具有该项目 ID 的每一行重复,反之亦然。因此,为什么您的计数很可能会关闭(因为由于连接的重复,它对给定表中的同一行进行了多次计数)。相反,您可能想尝试在两个子查询的结果之间进行联接,一个子查询按项目 ID 对第一个表进行分组并求和,第二个子查询按项目 ID 对另一个表进行分组并求和 - 然后联接一旦您只有 1 行包含每个项目 ID 的总和。
If you have
N
rows in AP with a given project ID, andM
rows in INV with that ID, then the join between the two tables on the project ID will have a total ofN*M
rows for that project, because the same row in AP will be repeated for every row in INV that has that project ID, and vice versa. Hence why your counts are most likely off (because it's counting the same row in a given table multiple times due to repetition from the join).Instead, you might want to try doing a join between the results of two subqueries, one which groups the first table by project ID and does that its sum, and the second which groups the other table by project ID and does that sum - then joining once you only have 1 row with sum for each project ID.
如果 PROJECT 是父表,则应从项目表中选择,并对两个子表执行左外连接:
If PROJECT is the parent table, you should select FROM the project table, and do a left outer join on the two child tables:
您可以将两个总和计算分开。我能想到的一种方法是将库存计算移至子查询,例如:
因为
SummedInv
子查询在project
上分组,所以在SummedInv 上分组是安全的.SUM_INV 也在外部查询中。
You could separate the two sum calculations. One way I can think of is to move the inventory calculation to a subquery, like:
Because the
SummedInv
subquery is grouped onproject
, it's safe to group onSummedInv.SUM_INV
in the outer query as well.这个查询怎么样:
这里是 ERD 的链接:http: //dl.dropbox.com/u/18794525/AUG%207%20DUMP%20STAN.png
how about this query :
here is the link to the ERD: http://dl.dropbox.com/u/18794525/AUG%207%20DUMP%20STAN.png
尝试:
Try: