MYSQL查询余额

时间:2014-03-29 19:54:01

标签: mysql

我的数据库中有两个表。

enter image description here

我想创建查询以显示余额,如:

enter image description here

我想:

  1. sum“order qty”
  2. 组“库存”项目
  3. 在“订单数量”
  4. 上显示“库存”项目为0

1 个答案:

答案 0 :(得分:1)

经过测试和工作:

SELECT inventory.inv_id, inventory.item, inventory.qty, 
COALESCE(SUM( `order`.qty ) , 0 ) AS sum_qty, 
COALESCE((inventory.qty - SUM( `order`.qty)) , 0) AS balance
FROM inventory
LEFT JOIN `order` ON inventory.inv_id = `order`.inv_id
GROUP BY `inventory`.inv_id
ORDER BY inventory.inv_id ASC