简体   繁体   English

从3个表中求和的SQL查询

[英]SQL query of Sum from 3 tables

I have following 3 tables 我有以下3张桌子

ITEM table
===========
id   desc
===========


IN table
=======================
id    id_item    number
=======================


OUT table
=========================
id     id_item    number
=========================

and this data on 这个数据在

item: 1 - GECO 项目:1-GECO

in: 1 - 1 - 40 2 - 1 - 2 在:1-1-40 2-1-2

out: 1 - 1 - 3 2 - 1 - 2 3 - 1 - 3 4 - 1 - 2 出:1-3 2-3 1-2 3-1 3-4 1-2

This is my query: 这是我的查询:

SELECT item.id,
       SUM(in.number) AS Sum_IN,
       SUM(out.number) AS Sum_OUT,
       (SUM(in.number) - SUM(out.number)) AS Dif
FROM item
LEFT OUTER JOIN IN ON item.id = IN.id_item
LEFT OUTER JOIN OUT ON item.id = OUT.id_item
GROUP BY item.id

And tis is the result tis是结果

id - Sum_IN - Sum_OUT id-Sum_IN-Sum_OUT

1 - 168 - 20 1-168-20

But i want 但我想要

id - Sum_IN - Sum_OUT id-Sum_IN-Sum_OUT

1 - 42 - 10 1-42-10

Where is the problem in my query? 查询中的问题出在哪里?

Try with INNER JOIN like 像这样尝试INNER JOIN

SELECT `item`.`id`,
       SUM(`in`.`number`) AS Sum_IN,
       SUM(`out`.`number`) AS Sum_OUT
FROM item
INNER JOIN `IN` ON item.id = `IN`.id_item
INNER JOIN `OUT` ON item.id = `OUT`.id_item
GROUP BY item.id
SELECT item.id, A.Sum_IN, B.Sum_OUT, (A.Sum_IN - B.Sum_OUT) AS Dif 
from item 
left outer join(
select  id_item as id, SUM(number) AS Sum_IN
FROM in   GROUP BY id_item) as A ON item.id = A.id
 left outer join(
select  id_item as id, SUM(number) AS Sum_OUT
FROM out  GROUP BY id_item) as B ON item.id = B.id

You have two IN records and 4 OUT records. 您有两个IN记录和4个OUT记录。 You join them, so you get 8 records in total. 加入他们,您总共可以获得8条记录。 You get each OUT record twice and each IN record four-fold in this intermediate result. 在此中间结果中,每个OUT记录两次,每个IN记录四倍。 Thus your sums are multiplied when you aggregate. 因此,当您汇总时,您的总和就会成倍增加。 You can divide by the number of joined records to get back to the original sums: 您可以用联接记录的数量除以返回原始总和:

SUM(in.number) / COUNT(DISTINCT OUT.id) AS Sum_IN,
SUM(out.number) / COUNT(DISTINCT IN.id) AS Sum_OUT,

This works, but is rather strange to read. 这行得通,但是读起来很奇怪。 The question is: Why do you join all those single records, when you are only interested in their sums? 问题是:当您只对它们的总和感兴趣时,为什么要加入所有这些单个记录? Use derived tables instead that hold the already aggregated data , ie the sums: 请改用派生表来保存已经聚合的数据,即总和:

select 
  item.id,
  in_sum.value as sum_in,
  out_sum.value as sum_out,
  in_sum.value - out_sum.value as dif
from item
left outer join (select id_item, sum(number) as value from in group by id_item) in_sum
  on item.id = in_sum.id_item
left outer join (select id_item, sum(number) as value from out group by id_item) out_sum
  on item.id = out_sum.id_item
group by item.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM