SQL 子查询(入库数量运行时按商店汇总入库和出库,然后从入库减去出库)

SQL subquery (stockin quantity runtime by sum up the stock in and stock out group by store and than subtract from stockin to stock out)

我有 2 tables 入库和出库我想计算入库数量运行时间,方法是按商店汇总入库和出库,然后从入库中减去出库。 我的查询运行良好,但是当它没有发现任何缺货记录时 table 它会进行一些不寻常的计算

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 (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;

也许这会解决您的问题。

这个

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

从 Items_Store 得到 Item_ID。如果它为 null(我想这永远不会是这种情况),则将其替换为 0。如果找不到任何记录,则会得到 NULL。

将其替换为

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

但是正如 Gordon 已经提到的,最好简化您的查询。

编辑:看来您在链接表格时并未使用所有标准。看这里:

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;

items_store 必须由 store_id 和 item_id 链接。