我有两个表,库存和库存,我想计算库存的数量运行时,通过总结库存和库存分组,并减去从库存到库存.我的查询运行良好,但是当它在库存表中找不到任何记录时,它会做一些不寻常的计算。
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发布于 2015-05-13 13:43:28
这
(select ISNULL(Items_store.Item_ID,0) from Items_Store where ...)从Item_ID获得Items_Store的信息。如果它是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连接。
发布于 2015-05-13 13:37:48
只需执行以下操作,就可以大大简化查询:
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;也许这会解决你的问题。
https://stackoverflow.com/questions/30216181
复制相似问题