如何从以下架构中获取特定商店中的某些商品余额?
item balance = ItemOpeningBalances.OpeiningBalance + PurchaseOrderDetails.ReceivedQuantity
我尝试使用以下查询获得余额,但它在余额中为null
提供了值
查询
SELECT
i.ItemID,
s.StoreID,
SUM(iob.OpeiningBalance + pod.ReceivedQuantity) AS balance
FROM
dbo.StoreDetails st
LEFT JOIN
Stores s ON st.StoreID = s.StoreID
LEFT JOIN
PurchaseOrders po ON st.PurchaseOrderID = po.PurchaseOrderID
LEFT JOIN
PurchaseOrderDetails pod ON po.PurchaseOrderID = pod.PurchaseOrderID
LEFT JOIN
Items i ON pod.ItemID = i.ItemID
LEFT JOIN
ItemOpeningBalances iob ON st.OpeiningBalanceID = iob.OpeiningBalanceID
AND i.ItemID = iob.ItemID
WHERE
(i.ItemID = 1)
AND (s.StoreID = 1)
GROUP BY
i.ItemID, s.StoreID
输出
ItemID StoreID balance
1 1 Null
模式
答案 0 :(得分:1)
可能会发生这种情况,因为加null
的任何内容都是null
。
试试这个:
SELECT
i.ItemID,
s.StoreID,
SUM(COALESCE(iob.OpeiningBalance,0) + COALESCE(pod.ReceivedQuantity,0) AS balance
FROM dbo.StoreDetails st
LEFT JOIN Stores s
ON st.StoreID = s.StoreID
LEFT JOIN PurchaseOrders po
ON st.PurchaseOrderID = po.PurchaseOrderID
LEFT JOIN PurchaseOrderDetails pod
ON po.PurchaseOrderID = pod.PurchaseOrderID
LEFT JOIN Items i
ON pod.ItemID = i.ItemID
LEFT JOIN ItemOpeningBalances iob
ON st.OpeiningBalanceID = iob.OpeiningBalanceID
AND i.ItemID = iob.ItemID
WHERE (i.ItemID = 1)
AND (s.StoreID = 1)
GROUP BY i.ItemID,
s.StoreID