我正在使用以下代码: table1-add,table2-remove
SELECT add.description, add.size, (sum(add.qty) - sum(remove.qty)) AS OnHand
`FROM add LEFT JOIN remove ON (add.description = remove.description) AND `(add.size = remove.size)
group by add.description, add.size
OnHand FROM add RIGHT JOIN remove ON (add.description = remove.description) AND
(add.size = remove.size) WHERE add.description IS NULL and add.size is null
group by add.description, add.size;
标题是我的目标。
我尝试了其他几种方法,但是在减法之前不会对列求和。它只减去第一个匹配项。
其他方法:
SELECT add.description, add.size, sum(add.qty) - sum(remove.qty) AS OnHand
FROM add INNER JOIN remove
ON add.description = remove.description
WHERE add.size = remove.size
GROUP BY add.description, add.size;
答案 0 :(得分:0)
您似乎需要先进行分组,以计算每个表的总和-然后进行相减;
SELECT t1.description, t1.size, (sum_add - sum_rem) AS OnHand
FROM
( SELECT add.description, add.size, sum(add.qty) as sum_add from add GROUP BY add.description, add.size )t1
INNER JOIN
( SELECT remove.description, remove.size, sum(remove.qty) as sum_rem from remove GROUP BY remove.description, remove.size )t2
ON t1.description = t2.description and t1.size = t2.size
代码未经测试,可能可以通过更好的方式完成-但这应该可以工作。