SQL子查询(按存储汇总入库和出库组,然后从入库到出库减去入库数量运行时)
我有两个表stockin和stockout我想计算stockin QUOTE运行时的库存量,方法是按门店汇总进货和出库组,然后从stockin中减去stockout。。 我的查询运行良好,但当它在缺货表中找不到任何记录时,它会进行一些不寻常的计算SQL子查询(按存储汇总入库和出库组,然后从入库到出库减去入库数量运行时),sql,switch-statement,subquery,inner-join,correlated-subquery,Sql,Switch Statement,Subquery,Inner Join,Correlated Subquery,我有两个表stockin和stockout我想计算stockin QUOTE运行时的库存量,方法是按门店汇总进货和出库组,然后从stockin中减去stockout。。 我的查询运行良好,但当它在缺货表中找不到任何记录时,它会进行一些不寻常的计算 Select CASE WHEN (select ISNULL(Items_store.Item_ID,0) from Items_Store where Items_Store.Store_ID = Inventory_Inco
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\u商店获取Items\u 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;
物品商店必须同时通过商店id和物品id链接。谢谢您的回复,但问题仍然存在。如果在物品商店表中找不到物品id,请在减号中入库。。如果找不到,则只需返回inventoryincoming Table中的总和。它仍然给出负数。如果找不到,则只需返回inventoryincoming Table中的总和。请查看我编辑的答案。您减去的项目太多:-