来自表的SUM值,并将其减去另一个具有相同ID

时间:2015-10-07 03:41:18

标签: c# sql ms-access-2010

我有两个表,inventory_tbl和withdraw_tbl,都有product_id,数量和金额。我想将inventory_tbl的所有数量相加并将其减去loan_tbl中两个表具有相同product_id的所有数量的总和。含义;

inventory_tbl

product_id | quantity  | amount
1          | 10        | 10000
2          | 20        | 20000
3          | 30        | 30000

withdrawal_tbl

product_id | quantity  | amount
1          | 5         | 5000
2          | 10        | 10000
3          | 20        | 20000

Remaining_tbl

product_id | quantity  | amount
1          | 5         | 5000
2          | 10        | 10000
3          | 10        | 10000

到目前为止,我有这个SQL语句,但它给了我错误的信息

"SELECT inventory_tbl.product_id As 'Product ID', SUM(inventory_tbl.quantity) - SUM(withdrawal_tbl.quantity), SUM(inventory_tbl.total) - SUM(withdrawal_tbl.total) 
FROM withdrawal_tbl, inventory_tbl GROUP BY inventory_tbl.product_id"

谢谢!

2 个答案:

答案 0 :(得分:2)

你正在做Cross Product而不是Inner join这就是问题所在。

将您的查询更改为此类

"SELECT inventory_tbl.product_id As 'Product ID', SUM(inventory_tbl.quantity) - SUM(withdrawal_tbl.quantity), SUM(inventory_tbl.total) - SUM(withdrawal_tbl.total) 
FROM withdrawal_tbl inner join inventory_tbl on inventory_tbl.product_id = withdrawal_tbl.product_id  GROUP BY inventory_tbl.product_id"

答案 1 :(得分:0)

使用内部连接获得所需的输出,试试这个:

"SELECT inventory_tbl.product_id As 'Product ID', SUM(inventory_tbl.quantity) - SUM(withdrawal_tbl.quantity), SUM(inventory_tbl.total) - SUM(withdrawal_tbl.total) 
FROM inventory_tbl INNER JOIN withdrawal_tbl on inventory_tbl.product_id =withdrawal_tbl.product_id group by inventory_tbl.product_id;"