在三个表上使用sql join

时间:2017-02-28 06:07:10

标签: sql sql-server sql-server-2012 inner-join

我有3个表来维护每个产品/项目的库存条目。这三个表格如下:

Table : ItemStock (to maintain remaining stock of each item)

Id  ItemId  OpgQty  BranchID  CurrentStock
1     7       0       1            8
2     7       0       2            3
3     6       0       1            2
4     6       0       2            0

Table : ItemPurchase (StockIn)

    Id  ItemId   Qty  BranchID  
    1     7       5       1            
    2     7       4       2   
    3     7       6       1  
    4     7       2       2          
    5     6       4       1           
    6     6       2       2           
    7     6       2       1  

表:ItemSale(StockOut)

    Id  ItemId   Qty  BranchID  
    1     7       2       1            
    2     7       3       2   
    3     7       1       1  
    4     6       4       1           
    5     6       2       2           

期望输出(基于sql查询)
我希望得到如下结果:(报告的一部分)

Id ItemId  OpgQty  BranchId StockIn  StockOut  CurrentStock
1    7       0        1        11       3           8
2    7       0        2        6        3           3
3    6       0        1        6        4           2
4    6       0        2        2        2           0

我试图获得理想的结果,但却无法做到。请帮忙!!!

4 个答案:

答案 0 :(得分:1)

试试这个;

select
m.Id,
m.ItemId,
m.OpgQty,
m.BranchID,
si.StockIn,
m.CurrentStock-si.StockIn StockOut,
m.CurrentStock
from
ItemStock m
inner join
(
select 
ItemId,BranchId,sum(Qty) as StockIn
from
ItemPurchase
group by ItemId,BranchId
) si on si.ItemId=m.ItemId and si.BranchId=m.BranchId 

答案 1 :(得分:1)

提供所需结果的非常简单的查询是:

select *,
       (select sum(Qty) 
        from ItemPurchase 
        where ItemPurchase.ItemId = ItemStock.ItemId and 
              ItemPurchase.BranchId = ItemStock.BranchId) as StockIn,
       (select sum(Qty) 
        from ItemSale 
        where ItemSale.ItemId = ItemStock.ItemId and 
              ItemSale.BranchId = ItemStock.BranchId) as StockOut
from ItemStock

答案 2 :(得分:0)

具有select s.*, coalesce([ip].StockIn, 0) as StockIn, -- In case of no records in ItemPurchase or ItemSale, coalesce is neccessary. coalesce([is].StockOut, 0) as StockOut from ItemStock s left join ( select sum(Qty) as StockIn, ItemId, BranchId from ItemPurchase group by ItemId, BranchId ) [ip] on s.ItemId = [ip].ItemId and s.BranchId = [ip].BranchId left join ( select sum(Qty) as StockOut, ItemId, BranchId from ItemSale group by ItemId, BranchId ) [is] on s.ItemId = [is].ItemId and s.BranchId = [is].BranchId 和聚合的两个子查询将获得您想要的结果。

Internet Explorer 10

请参阅sqlfiddle中的demo

答案 3 :(得分:0)

请  Try This ...我希望你也考虑这一点。