SQL子查询(通过将股票库存和库存组列为商店,而不是从斯托克(Stockin)中扣除库存的数量运行时)



我有2个表stockin和stockout,我想通过总和库存和库存组来计算stockin的数量运行时,而不是从斯托克本中减去库存。我的查询运行良好,但是当它在库存的表格中找不到任何记录时,它会进行一些不寻常的计算

Select 
CASE 
    WHEN 
    (select ISNULL(Items_store.Item_ID,0) from Items_Store where Items_Store.Store_ID = Inventory_Incoming.Store_ID)
    <> 0
    THEN   
    SUM(Quentity)- 
    (select SUM(Items_Out) from Items_Store where Items_Store.Store_ID = Inventory_Incoming.Store_ID)
    ELSE
    SUM(Quentity) 
END as Stock 
,Store_ID,Item_ID
from Inventory_Incoming 
where Item_ID =1
group by 
Store_ID,
Item_ID

这个

(select ISNULL(Items_store.Item_ID,0) from Items_Store where ...)

从tooks_store获取item_id。如果它是零的(我想从来都不是这样),则您将其替换为0。如果找不到记录,您会得到零。

替换
ISNULL((select Items_store.Item_ID from Items_Store where ...), 0)

但是,正如戈登已经提到的那样,可以更好地简化查询。

编辑:链接表时似乎并未使用所有条件。请参阅此处:

select 
  sum(quentity) - 
  coalesce(
  (
    select sum(items_out) 
    from items_store is
    where is.store_id = ii.store_id and is.item_id = ii.item_id
  ), 0)
from inventory_incoming ii
where item_id =1
group by store_id, item_id;

tock_store必须由store_id和item_id链接。

您可以通过以下方式大大简化查询:

Select (sum(Quentity) - 
        coalesce((select SUM(Items_Out)
                  from Items_Store s
                  where s.Store_ID = ii.Store_ID
                 ), 0)
        ) as Stock, Store_ID, Item_ID
from Inventory_Incoming ii
where ii.Item_ID = 1
group by ii.Store_ID, ii.Item_ID;

也许这将解决您的问题。

最新更新