我有以下3个表
ITEM table
===========
id desc
===========
IN table
=======================
id id_item number
=======================
OUT table
=========================
id id_item number
=========================
和
上的这些数据项: 1 - GECO
在: 1 - 1 - 40 2 - 1 - 2
出: 1 - 1 - 3 2 - 1 - 2 3 - 1 - 3 4 - 1 - 2
这是我的疑问:
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
而结果是
id - Sum_IN - Sum_OUT
1 - 168 - 20
但我想要
id - Sum_IN - Sum_OUT
1 - 42 - 10
我的查询中的问题在哪里?
答案 0 :(得分:0)
尝试使用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
答案 1 :(得分:0)
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
答案 2 :(得分:0)
您有两条IN记录和4条OUT记录。你加入他们,所以你总共得到8条记录。在这个中间结果中,每次OUT记录两次,每次IN记录四次。因此,当您汇总时,您的总和会成倍增加。您可以除以连接记录的数量以返回原始总和:
SUM(in.number) / COUNT(DISTINCT OUT.id) AS Sum_IN,
SUM(out.number) / COUNT(DISTINCT IN.id) AS Sum_OUT,
这很有效,但读起来很奇怪。问题是:当你只对他们的金额感兴趣时,为什么要加入所有这些单一记录?使用派生表来保存已经聚合的数据,即总和:
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