我有以下SQL语句,其中我添加了游戏库存和订购的库存,然后选择具有低于再订货点的总库存的游戏。唯一的问题是我还想在没有任何订购库存的再订货点下面选择游戏库存。我试着弄乱了ItemIDs不匹配的Having行,但没有运气。这是当前的工作代码。
我有什么:
SELECT tblGames.ItemID, tblGames.Title, ABS(tblGames.Inventory + Sum(tblSupplyOrders.Inventory)) AS UpdatedInventory
FROM tblGames
INNER JOIN tblSupplyOrders
ON tblGames.ItemID=tblSupplyOrders.ItemID
Group By tblGames.ItemID, tblGames.Title, tblGames.Inventory, tblGames.ReorderPoint
Having ABS(tblGames.Inventory + Sum(tblSupplyOrders.Inventory)) < tblGames.ReorderPoint
我还想用它显示:
SELECT tblGames.ItemID, tblGames.Title, tblGames.Inventory
FROM tblGames
INNER JOIN tblSupplyOrders
ON tblGames.ItemID=tblSupplyOrders.ItemID
Group By tblGames.ItemID, tblGames.Title, tblGames.Inventory, tblGames.ReorderPoint
Having tblGames.Inventory < tblGames.ReorderPoint
...没有tblSupplyOrders.ItemID
提前致谢!
tblGames包括:
tblSupplyOrders包括:
所以如果:
答案 0 :(得分:2)
我认为你过于复杂了:
SELECT tg.ItemID, tg.Title, tg.Inventory
FROM tblGames tg
LEFT JOIN (
select ItemID, sum(inventory) as Inventory
from tblSupplyOrders
group by ItemID) tso
ON tg.ItemID=tso.ItemID
where tg.Inventory+coalesce(tso.Inventory,0) < tg.ReorderPoint
这会将tblGames
连接到tblSupplyOrders
的子查询,该子查询汇总特定项目的所有订单。这将返回tblGames
中的所有行以及来自tblSupplyOrders
的订单聚合的匹配行,其中没有匹配tso
行的空值。
表达式tg.Inventory+coalesce(tso.Inventory,0)
计算当前库存+挂单;需要coalesce
来处理没有tso
行的情况,对待处理的订单替换为零而不是null。