库存查询未显示确切结果

时间:2014-12-06 15:07:10

标签: sql sql-server

我使用此查询来维护我的库存,但它没有显示确切的结果

select p.Product_Name Product
      ,isnull(sum(d.qty),0) Purchase_Qty
      ,isnull(sum(i.qty),0) Issue_Qty
      ,(isnull(sum(d.qty),0)-isnull(sum(i.qty),0)) InStock
from purchase_dtl d 
left join issue_dpt i on i.Product_ID=d.Product_ID
right join product p on p.id = d.Product_ID
group by Product_Name

查询结果

Product | Purchase_Qty | Issue_Qty | InStock
---------------------------------------------
Pen           1000          300        700
Books         4000         1000       3000

我的确切购买数量

Product | Purchase_Qty
----------------------
Pen           500
Books        2000

我的确切问题数量

Product | Issue_Qty
-------------------
Pen          300
Books       1000

请帮我解决我的问题

由于

1 个答案:

答案 0 :(得分:0)

select p.Product_Name Product
      , p.Purchase_Qty
      , isnull(sum(i.qty),0) Issue_Qty
      , p.Purchase_Qty-isnull(sum(i.qty),0) InStock
from (select p.id, p.Product_Name, isnull(sum(d.qty),0) Purchase_Qty      
      from product p left join purchase_dtl d on p.id = d.Product_ID
      group by p.id, p.Product_Name) p
      left join issue_dpt i on i.Product_ID = p.id
group by Product_Name, p.Purchase_Qty

我想加入purchase_dtlissue_dpt会为Purchase_Qty

提供一些额外的行

首先加入product purchase_dtl以计算汇总数据,然后再次加入issue_dpt