gpt4 book ai didi

mysql - 根据匹配条件连接表,并从 Table1.Quantity 的总和中减去 Table2.Quantity 的总和以获取匹配行

转载 作者:行者123 更新时间:2023-11-29 16:11:02 27 4
gpt4 key购买 nike

我正在使用下面的代码:表1-添加,表2-删除

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;

最佳答案

看来您需要先进行分组,计算每个表的总和 - 然后进行减法;

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

代码未经测试,可能可以用更好的方式完成 - 但这应该可行。

关于mysql - 根据匹配条件连接表,并从 Table1.Quantity 的总和中减去 Table2.Quantity 的总和以获取匹配行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55263402/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com